0

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?

Zilberman Rafael
  • 1,341
  • 2
  • 14
  • 45

3 Answers3

3

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?

Community
  • 1
  • 1
V-SHY
  • 3,925
  • 4
  • 31
  • 47
0

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]);
}
joppiesaus
  • 5,471
  • 3
  • 26
  • 36
-2

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.

Mustafa Chelik
  • 2,113
  • 2
  • 17
  • 29
  • I wasn't talking about actual ascii. I was talking about ascii in the code. I wrote purposely this way to be easy to understand. I know there is nothing called ascii unsigned char. – Mustafa Chelik Mar 01 '14 at 19:25
  • in c, refer answer @Adrian McCarthy, http://stackoverflow.com/questions/13161199/ascii-table-negative-value There is no such thing as a "negative ASCII" value. ASCII defines character and control codes for values from 0 to 127. therefore your answer has problem on **signed** char – V-SHY Apr 22 '14 at 01:21