0
votes

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



}
2
Possible duplicate of Byte[] to ASCIIPaulF
Well maybe , but its not the same , and i have hard time implementing that solution to here , could someone explain me howIvanh23
Why is it not the same?PaulF
since rxbytearray is an array of bytes, you can just do hexvalues = hexvalues + (char)b + " ";, or you could do what is in fstam's answerabsoluteAquarian
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

2 Answers

3
votes
Encoding.ASCII.GetString(byteArray);
0
votes

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