Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to stick to binary files then <strong>don't use <code>StreamWriter</code></strong>. Just use a <code>FileStream</code> and <code>Write</code>/<code>WriteByte</code>. StreamWriters (and TextWriters in generally) are expressly designed for <em>text</em>. Whether you want an encoding or not, one will be applied - because when you're calling <code>StreamWriter.Write</code>, that's writing a <code>char</code>, not a <code>byte</code>.</p> <p>Don't create arrays of <code>wchar_t</code> values either - again, those are for <em>characters</em>, i.e. text.</p> <p><code>BinaryWriter.Write</code> should have worked for you unless it was promoting the values to <code>char</code> in which case you'd have exactly the same problem.</p> <p>By the way, without specifying <em>any</em> encoding, I'd expect you to get non-0x3F values, but instead the bytes representing the UTF-8 encoded values for those characters.</p> <p>When you specified <code>Encoding.Default</code>, you'd have seen 0x3F for any Unicode values not in that encoding.</p> <p>Anyway, the basic lesson is to stick to <code>Stream</code> when you want to deal with binary data rather than text.</p> <p>EDIT: Okay, it would be something like:</p> <pre><code>public static void ConvertHex(TextReader input, Stream output) { while (true) { int firstNybble = input.Read(); if (firstNybble == -1) { return; } int secondNybble = input.Read(); if (secondNybble == -1) { throw new IOException("Reader finished half way through a byte"); } int value = (ParseNybble(firstNybble) &lt;&lt; 4) + ParseNybble(secondNybble); output.WriteByte((byte) value); } } // value would actually be a char, but as we've got an int in the above code, // it just makes things a bit easier private static int ParseNybble(int value) { if (value &gt;= '0' &amp;&amp; value &lt;= '9') return value - '0'; if (value &gt;= 'A' &amp;&amp; value &lt;= 'F') return value - 'A' + 10; if (value &gt;= 'a' &amp;&amp; value &lt;= 'f') return value - 'a' + 10; throw new ArgumentException("Invalid nybble: " + (char) value); } </code></pre> <p>This is very inefficient in terms of buffering etc, but should get you started.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload