Convert int to byte as HEX in C#

有些话、适合烂在心里 提交于 2019-12-08 01:57:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!