Convert ASCII in a byte array to string

后端 未结 3 587
囚心锁ツ
囚心锁ツ 2021-01-19 15:51

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

3条回答
  •  不思量自难忘°
    2021-01-19 16:31

    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())

提交回复
热议问题