Maddie
Maddie

Reputation: 69

can not convert byte array to string and vice versa

I am trying to convert byte array to string but bytes are not being converted to string correctly.

byte[] testByte = new byte[]
{
    2, 200
};

string string1 = Encoding.ASCII.GetString(testByte);
byte[] byte1 = Encoding.ASCII.GetBytes(string1);

string1 is giving value as \u0002? and byte1 is not getting converted back to 2 and 200. I tried with UTF8 but that is also giving same problem.

I have been given 256 array of chars and integer values. I need to write these values on media as string and read back as bytes. I need conversion to write and read byte data. I am facing problems when integer value comes more then 127.

What should I do so I get original byte values from string?

Upvotes: 0

Views: 1170

Answers (2)

well the problem here is your bite string retrieval chain fix this and then it will fix itself by removing the false elseif! hope this helps

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064114

You appear to be using an encoding backwards. A text Encoding(such as ASCII) is for converting arbitrary text data into encoded (meaning: specially formatted) binary data.

(a caveat should be included here that not all encodings support all text characters; ASCII only supports code-points 0-128, for example, but that isn't the main problem with the code shown)

You appear to want to treat arbitrary binary data as a string - which is the exact opposite. Arbitrary binary data, and encoded text data. Not a problem: just use base-N for some N. Hex (base-16) would work, but base-64 will be more space efficient:

string encoded = Convert.ToBase64String(testByte);
byte[] decoded = Convert.FromBase64String(encoded);

Upvotes: 1

Related Questions