9

I seem to be having problems with my string conversions in C#. My application has received a byte array consisting of an ASCII string (one byte per character). Unfortunately it also has a 0 in the first location. So how do I convert this byte array to a c# string? Below is a sample of the data I am trying to convert:

byte[] exampleByteArray = new byte[] { 0x00, 0x52, 0x50, 0x4D, 0x20, 0x3D, 0x20, 0x32, 0x35, 0x35, 0x2C, 0x36, 0x30, 0x0A, 0x00 };
string myString = null;

I have made several unsuccessful attempts, so thought I would ask for assistance. Eventually I need to add the string to a listbox:

listBox.Items.Add(myString);

The desired output in the listBox: "RPM = 255,630" (with or without the linefeed). The byte array will be variable length, but will always be terminated with 0x00

0

3 Answers 3

14
byte[] exampleByteArray = new byte[] { 0x00, 0x52, 0x50, 0x4D, 0x20, 0x3D, 0x20, 0x32, 0x35, 0x35, 0x2C, 0x36, 0x30, 0x0A, 0x00 };
exampleByteArray = exampleByteArray.Where(x=>x!=0x00).ToArray(); // not sure this is OK with your requirements 
string myString =  System.Text.Encoding.ASCII.GetString(exampleByteArray).Trim();

Result :

RPM = 255,60

you can add this to listBox

listBox.Items.Add(myString);

Update :

As per new comment byte array can contain garbage after the trailing 0x00 (remnants of previous strings).

You need to skip first 0x00 and then consider bytes until you get 0x00, so you can use power of Linq to do this task. e.g ASCII.GetString(exampleByteArray.Skip(1).TakeWhile(x => x != 0x00).ToArray())

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

2 Comments

Oh, so close! I forgot to mention that the byte array can contain garbage after the trailing 0x00 (remnants of previous strings)...
This sure beats a for loop, THANKS!
1
 byte[] exampleByteArray = new byte[] { 0x00, 0x52, 0x50, 0x4D, 0x20, 0x3D, 0x20, 0x32, 0x35, 0x35, 0x2C, 0x36, 0x30, 0x0A, 0x00 };
 string myString = System.Text.ASCIIEncoding.Default.GetString(exampleByteArray);

Result: myString = "\0RPM = 255,60\n\0"

Comments

1
var buffer = new byte[] { 0x00, 0x52, 0x50, 0x4D, 0x20, 0x3D, 0x20, 0x32, 0x35, 0x35, 0x2C, 0x36, 0x30, 0x0A, 0x00 }
    .Skip(1)
    .TakeWhile(b => b != 0x00).ToArray();

Console.WriteLine(System.Text.Encoding.ASCII.GetString(buffer));

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.