0

So I am trying to split a string and send the values as bytes to the serial port .

I have found a few solution's and examples but I just can get it to work with my values .

This is the code I am trying, the problem is the 255 seems to generate an error saying . I have try a few thing but just cant seem to figure this out.

Activated Event Time Duration Thread Exception: Exception thrown: 'System.OverflowException' in mscorlib.dll ("Value was either too large or too small for an unsigned byte."). Exception thrown: 'System.OverflowException' in mscorlib.dll ("Value was either too large or too small for an unsigned byte.") 8.67s [9972] Worker Thread

SerialPort _SP;
_SP = SerialConnect(SelectedPort, 9600);


string str = "0xFE 0xD0 0x255 0x0 0x0";

byte[] bytes = str.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();

_SP.Write(bytes, 0, bytes.Length);

3 Answers 3

2

0x255 in hexadecimal is equal to 597 in decimal, which IS too big for a byte. You're probably looking for hexadecimal 0xFF, which is equal to 255 in decimal. If you want to know how to figure this out yourself, I recommend reading up on hexadecimal.

  • floor(255 / 16^1) = 15 (F)
  • 255 - 15 * 16 = 15
  • floor(15 / 16^0) = 15 (F)

hence, 0xFF, also be aware of the endian-ness you are working with: https://en.wikipedia.org/wiki/Endianness

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

2 Comments

Thanks that might work , I will have to give it a try . I am following this guide and it lists the values to send as "0xFE 0xD0 0x255 0x0 0x0"
Well, now you know that you need to be careful when reading technical things. Sometimes people writing these things make typos, and sometimes they don't understand how different numeric bases work.
0

See corrected code below:

var bytes = new byte[] { 0xFE, 0xD0, 0xFF, 0x0, 0x0 };
var port = SerialConnect(SelectedPort, 9600);
port.Write(bytes, 0, bytes.Length);

If you really needed 6 bytes (0x255 not being an error):

var bytes = new byte[] { 0xFE, 0xD0, 0x2, 0x55, 0x0, 0x0 };
var port = SerialConnect(SelectedPort, 9600);
port.Write(bytes, 0, bytes.Length);

Comments

0

Hi the max hex value you can hold in 2bytes is 0xFF thats the reason you get an exception when you try to convert 0x255 to hex

Comments

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.