C # ByteArray to convert strings and back

I have a uint value that I need to represent as ByteArray and convert to a string. When I convert a string to an array of bytes, I found different values. I use the standard ASCII converter, so I don’t understand why I have different values. To be more clear, this is what I am doing:

byte[] bArray = BitConverter.GetBytes((uint)49694); string test = System.Text.Encoding.ASCII.GetString(bArray); byte[] result = Encoding.ASCII.GetBytes(test); 

The result of bytearray is different from the first:

bArray β†’

 [0x00000000]: 0x1e [0x00000001]: 0xc2 [0x00000002]: 0x00 [0x00000003]: 0x00 

result β†’

 [0x00000000]: 0x1e [0x00000001]: 0x3f [0x00000002]: 0x00 [0x00000003]: 0x00 

Note that byte 1 is different in two arrays.

Thanks for your support.

Hello

+4
source share
2 answers
 string test = System.Text.Encoding.ASCII.GetString(bArray); byte[] result = Encoding.ASCII.GetBytes(test); 

Because the source data is not ASCII . Encoding.GetString only meaningful if the data you decode is text data in this encoding. Anything else: you ruin it. If you want to save byte[] as a string , then you need to use base-n - usually base-64, because a: it is conveniently available ( Convert.{To|From}Base64String ) and b: you can put it in ASCII, so You rarely encounter codepage / encoding issues. For instance:

 byte[] bArray = BitConverter.GetBytes((uint)49694); string test = Convert.ToBase64String(bArray); // "HsIAAA==" byte[] result = Convert.FromBase64String(test); 
+11
source
 Because c2 is not a valid ASCII char and it is replaced with '?'(3f) 

Converting any byte array to a string using SomeEncoding.GetString() not a safe method like @activwerx suggested in the comments. Use Convert.FromBase64String , Convert.ToBase64String instead

+3
source

Source: https://habr.com/ru/post/1445508/


All Articles