Question

I don't know why but when you do the next thing you will never get the same as the original byte array:

var b = new byte[] {252, 2, 56, 8, 9};
var g = System.Text.Encoding.ASCII.GetChars(b);
var f = System.Text.Encoding.ASCII.GetBytes(g);

If you will run this code you will see that b != f, Why?! Is there any way to convert bytes to chars and then back to bytes and get the same as the original byte array?

Was it helpful?

Solution

byte value can be 0 to 255.

When the byte value > 127, then result of

System.Text.Encoding.ASCII.GetChars()

is always '?' which has value 63

Therefore,

System.Text.Encoding.ASCII.GetBytes()

result always get 63 (wrong value) for those have initial byte value > 127


If you need TABLE ASCII -II then you can do as following

        var b = new byte[] { 252, 2, 56, 8, 9 };
        //another encoding
        var e = Encoding.GetEncoding("437");
        //252 inside the mentioned table is ⁿ and now you have it
        var g = e.GetString(b);
        //now you can get the byte value 252
        var f = e.GetBytes(g);

Similar posts you can read

How to convert the byte 255 to a signed char in C#

How can I convert extended ascii to a System.String?

OTHER TIPS

Why not use chars?

var b = new byte[] {252, 2, 56, 8, 9};
var g = new char[b.Length];
var f = new byte[g.Length]; // can also be b.Length, doens't really matter
for (int i = 0; i < b.Length; i++)
{
   g[i] = Convert.ToChar(b[i]);
}
for (int i = 0; i < f.Length; i++)
{
   f[i] = Convert.ToByte(g[i]);
}

The only difference is first byte: 252. Because ascii char is 1-byte signed char and it's value range is -128 to 127. Actually your input is incorrect. signed char can't be 252.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top