Convert ASCII to byte array to string

I seem to have problems with my string conversions in C #. My application received an array of bytes consisting of an ASCII string (one byte per character). Unfortunately, it also has 0 in the first place. So, how do I convert this byte array to a C # string? The following is a sample of the data I'm 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 made several unsuccessful attempts, so I thought I would ask for help. In the end I need to add a line to the list:

 listBox.Items.Add(myString); 

Desired result in listBox: "RPM = 255,630" (with or without line feed). The byte array will be variable length, but will always end in 0x00

+4
source share
3 answers
 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:

According to the new byte, the byte of the byte may contain garbage after the final 0x00 (the remains of the previous lines).

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

+10
source
  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"

0
source
 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)); 
0
source

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


All Articles