tags:

views:

63

answers:

2

I am reading data from a socket (as bytes) and storing this data in a string. Then later i need to access specific bytes within the string and do some math with them. However the bytes that I read back from the string are not what I am expecting.

Here's code to demonstrate my problem:

    Dim bytTest() As Byte = {131, 0}
    Dim strTest As String
    strTest = System.Text.ASCIIEncoding.ASCII.GetString(bytTest)
    MsgBox(bytTest(0) & " = " & Asc(strTest.Substring(0, 1)))

This produces "131 = 63", but I would have expected it to produce "131 = 131". Can somebody explain to me why and how I can fix this? Thanks

+1  A: 

ASCIIEncoding is limited to the first 7 bits (characters 0-127), so trying to store character with a value of 131 isn't going to work as expected.

Use UTF-8 instead.

richardtallent
no need for UTF-8, all i needed was System.Text.Encoding.GetEncoding(1252) instead of ASCII
Brian
+1  A: 

The ASCII encoding only uses the lower 7 bits of a byte for each character. Thus, if you pass a byte with value 131 to it, you will get unexpected results, since the high bit is set for that value.

Konamiman