2

Example, I want to convert 3 bytes to ASCII conversion

int a = random.Next(0, 100);
int b = random.Next(0, 1000);
int c = random.Next(0, 30);

byte[] byte1 = BitConverter.GetBytes(a);
byte[] byte2 = BitConverter.GetBytes(b);
byte[] byte3 = BitConverter.GetBytes(c);

byte[] bytes = byte1.Concat(byte2).Concat(byte3).ToArray();
string asciiString = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
label1.Text = asciiString;

It only shows byte1 instead of all bytes.

7
  • 1
    What are a, b and c? Commented Jun 17, 2019 at 8:32
  • 1
    What is a,b,c? Look into array bytes - it's probably unicode, so Encoding.ASCII is wrong. Commented Jun 17, 2019 at 8:33
  • 1
    please include that in your example Commented Jun 17, 2019 at 8:38
  • 3
    In general, converting arbitrary binary data into text using Encoding is a bad idea. Assuming you want to be able to get back the original binary data, I'd advise Convert.ToBase64String instead. Commented Jun 17, 2019 at 8:39
  • 2
    random values are not a good example to show your specific error. Commented Jun 17, 2019 at 9:01

1 Answer 1

4

If you look in the debugger at your asciiString variable you will see that all the 3 letters are there, but in between you always have a 0x00 char.

(screenshot from LINQPad Dump)

enter image description here

This is unfortunately interpreted as end of string. So this is why you see only the first byte/letter.

The documentation of GetBytes(char) says that it returns:

An array of bytes with length 2.

if you now get the bytes from a single char:

byte[] byte1 = BitConverter.GetBytes('a');

You get the following result:

enter image description here

The solution would be to pick only the bytes that are not 0x00:

bytes = bytes.Where(x => x != 0x00).ToArray();

string asciiString = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
label1.Text = asciiString;

This example is based on the char variant of GetBytes. But it holds for all other overloads of this method. They all return an array which can hold the maximum value of the corresponding data type. So this will happen always if the value is so small that the last byte in the array is not used and ends up to be 0!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.