0

i am receiving bytes from the serial port on my c# , and i am storing them in a byte array and then making them as string so now i need to convert the bytes to ASCII how i can do that? This is my code

void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) {

    string bytestr = "";

    int numbytes = serialPort1.BytesToRead;
    byte[] rxbytearray = new byte[numbytes];



    for (int i = 0; i < numbytes; i++)
    {
        rxbytearray[i] = (byte)serialPort1.ReadByte();

    }

    string hexvalues = "";
    foreach (byte b in rxbytearray)
    {
        if (b != '\r')
            hexvalues = hexvalues + (b.ToString()) + " ";



    }       //  hexvalues = richTextBox1.Text;

    Thread.Sleep(500);

    MessageBox.Show(hexvalues);



}
Ivanh23
  • 17
  • 6
  • 1
    Possible duplicate of [Byte\[\] to ASCII](https://stackoverflow.com/questions/6554869/byte-to-ascii) – PaulF Nov 12 '18 at 14:03
  • Well maybe , but its not the same , and i have hard time implementing that solution to here , could someone explain me how – Ivanh23 Nov 12 '18 at 14:04
  • Why is it not the same? – PaulF Nov 12 '18 at 14:05
  • since `rxbytearray` is an array of `byte`s, you can just do `hexvalues = hexvalues + (char)b + " ";`, or you could do what is in **fstam**'s answer – absoluteAquarian Nov 12 '18 at 14:10
  • 1
    SerialPort already uses Encoding.ASCII by default. It is not clear why you don't favor ReadChar() instead. Just keep the universal trap in mind, you in general need to read the *full* response of the device before you start processing it. That makes it quite likely that you should use ReadLine() or ReadTo(). Consult the device's programming manual to see how it packages messages. – Hans Passant Nov 12 '18 at 14:19
  • Interestingly ReadChar gives you not a Char but an Int ... – Andreas Nov 12 '18 at 14:25

2 Answers2

3
Encoding.ASCII.GetString(byteArray);
fstam
  • 669
  • 4
  • 20
0

I'd do it this way:

class SomeClass
{
  private StringBuilder _sb = new StringBuilder();
  private SerialPort serialPort1 

  [...]

  void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) 
  {
    if (e.EventType == SerialData.Chars)
    {
       _sb.Append(serialPort1.ReadExisting());
    }
    else
    {
       MessageBox.Show(_sb.ToString());
       _sb.Clear();
    }
  }
}
Andreas
  • 828
  • 4
  • 15