问题
I need to send a Hex string over the serial to a device, I do that now like this:
byte[] c = new byte[3];
c[0] = 0x57;
c[1] = 0x30;
ComPort.Write(c,0,c.Length );
Now I need to convert a value of int like 30 to c[1] = 0x30
or a int value of 34 gives c[1] = 0x34
.
I hope you see what I mean.
So how can I mange this?
回答1:
This format is called binary-coded decimal. For two-digit numbers, integer-divide by ten and multiply by sixteen, then add back the remainder of the division by ten:
int num = 45;
int bcdNum = 16*(num/10)+(num%10);
回答2:
Another way to do this could be
c[1] = Convert.ToByte(num.ToString(), 16);
回答3:
suppose int Data=2821; was to send over COM Port:
c[0]= Convert.ToByte(data & 0x00FF);
c[0]= Convert.ToByte(data & 0xFF00) >> 8);
ComPort.Write(c,0,c.Length );
来源:https://stackoverflow.com/questions/11794146/convert-int-to-byte-as-hex-in-c-sharp