Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm not sure ASCIIEncoding.GetBytes is going to do it, because it only supports the <a href="http://msdn.microsoft.com/en-us/library/system.text.asciiencoding.aspx" rel="nofollow noreferrer">range 0x0000 to 0x007F</a>. </p> <p>You tell the string contains only bytes. But a .NET string is an array of chars, and 1 char is 2 bytes (because a .NET stores strings as UTF16). So you can either have two situations for storing the bytes 0x42 and 0x98:</p> <ol> <li>The string was an ANSI string and contained bytes and is converted to an unicode string, thus the bytes will be 0x00 0x42 0x00 0x98. (The string is stored as 0x0042 and 0x0098)</li> <li>The string was just a byte array which you typecasted or just recieved to an string and thus became the following bytes 0x42 0x98. (The string is stored as 0x9842)</li> </ol> <p>In the first situation on the result would be 0x42 and 0x3F (ascii for "B?"). The second situation would result in 0x3F (ascii for "?"). This is logical, because the chars are outside of the valid ascii range and the encoder does not know what to do with those values.</p> <p>So i'm wondering why it's a string with bytes?</p> <ul> <li>Maybe it contains a byte encoded as a string (for instance <a href="http://en.wikipedia.org/wiki/Base64" rel="nofollow noreferrer">Base64</a>)?</li> <li>Maybe you should start with an char array or a byte array?</li> </ul> <p>If you realy do have situation 2 and you want to get the bytes out of it you should use the <a href="http://msdn.microsoft.com/en-us/library/system.text.unicodeencoding.getbytes.aspx" rel="nofollow noreferrer">UnicodeEncoding.GetBytes</a> call. Because that will return 0x42 and 0x98.</p> <p>If you'd like to go from a char array to byte array, the fastest way would be Marshaling.. But that's not really nice, and uses double memory. </p> <pre><code>public Byte[] ConvertToBytes(Char[] source) { Byte[] result = new Byte[source.Length * sizeof(Char)]; IntPtr tempBuffer = Marshal.AllocHGlobal(result.Length); try { Marshal.Copy(source, 0, tempBuffer, source.Length); Marshal.Copy(tempBuffer, result, 0, result.Length); } finally { Marshal.FreeHGlobal(tempBuffer); } return result; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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