I am debugging a WebAPI method that returns a short array of bytes. In the test jQuery that calls the API I have a breakpoint set and can see the 'data' that is returned from the WebAPI call. In the watch window in Visual Studio (2013) the JavaScript variable 'data' is given type 'string'. I would like to see the string as a series of bytes, in 0x1A 0x00 0x45 style. How can I do that?
The string I am interested in rendering as a byte array is at the centre of the last row in this screenshot (the one that starts "ICAgl"):
I was looking to do the exact same thing and found this:
System.Text.Encoding.Ascii.GetBytes(data)
Hope this helps!
Using the ASCII encoding will clobber bytes above 127. So if you happen to have non-ASCII characters in your string (which is usually possible from a web api call,) you will see the wrong bytes in the array. Since C# strings are using 2-byte Unicode chars by default you should use the Unicode encoding to see the bytes behind a string. If you can get to the actual bytes coming from the source (e.g. maybe it came across the wire as a UTF8 bytes?) you'd be better off to look at those. But if it's coming to you as a C# string and that's what your going to work with then using the Unicode encoding will accurately show you the bytes for the string in memory.
For example. Here's a string with chars above 127 (curly double quotes), and bytes resulting from ASCII vs. Unicode encoding with a print out of the string after converting it back to a string. The ASCII is lossy.
string data = "I said \u201cHello\u201d";
byte[] dataArrASCII = System.Text.Encoding.ASCII.GetBytes(data);
byte[] dataArrUnicode = System.Text.Encoding.Unicode.GetBytes(data);
dataArrrASCII length: 14
49 20 73 61 69 64 20 3F: I said ?
48 65 6C 6C 6F 3F : Hello?
dataArrUnicode length: 28
49 00 20 00 73 00 61 00: I sa
69 00 64 00 20 00 1C 20: id “
48 00 65 00 6C 00 6C 00: Hell
6F 00 1D 20 : o”
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With