1

I'm new to C# and I built an application that receives bytes from a Serial Port and parses the bytes.

In one scenario, the application receives an array of bytes that represents a string. My idea is to convert the bytes to string ad visualise the string into a text box.

With this code:

textSerialNumber.Text = Encoding.UTF8.GetString(readData.payload, 0, readData.payload.Length);

I obtain the string but there is a problem: the first byte receive on the serial port is a 0x00 ( it represents an ack ). When i convert the payload (ack + string ) the first character is a NULL and text box assignments fails.

If I modify the code to start form the first element of the byte array:

textSerialNumber.Text = Encoding.UTF8.GetString(readData.payload, 1, readData.payload.Length);

Also in this case the text box assignment fails.

I try to skip the text box assignment:

string x = Encoding.UTF8.GetString(readData.payload, 1, readData.payload.Length);

But also int this case the encoding fails.

Any suggestion to find the error?

Thanks in advance.

3
  • try string base64 = Convert.ToBase64String(readData); Commented Oct 9, 2017 at 7:44
  • What does it mean "it fails"? Commented Oct 9, 2017 at 7:47
  • Fails means the the assignment procedure fails and the code reaches the catch statement. Commented Oct 9, 2017 at 7:49

1 Answer 1

3

Try string x = Encoding.UTF8.GetString(readData.payload, 1, readData.payload.Length - 1);

Last argument is count, so if you start from 1, count has to be 1 less.

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

2 Comments

Thanks Pavel! It works! But the assignemts into the text box fails: this is my string : "V2_1928608331\0\0\0\0\0\0\0\0\0\0\0\0\0".
I found the problem. C# means that another thread try to modify the textbox.

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.