简体   繁体   English

在 C# 中将 int 转换为字节为 HEX

[英]Convert int to byte as HEX in C#

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 .现在我需要将 30 之类的 int 值转换为c[1] = 0x30或 34 的 int 值给出c[1] = 0x34 I hope you see what I mean.我希望你明白我的意思。

So how can I mange this?那么我该如何管理呢?

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

另一种方法是

c[1] = Convert.ToByte(num.ToString(), 16);

suppose int Data=2821; 假设int Data = 2821; was to send over COM Port: 是通过COM端口发送的:

c[0]= Convert.ToByte(data & 0x00FF); 

c[0]= Convert.ToByte(data & 0xFF00) >> 8);

ComPort.Write(c,0,c.Length );
int num = 1366;
string bcdNum = num.ToString("X");
if (bcdNum.Length < 2)
bcdNum = "0" + bcdNum;
byte[] bytes_str=Enumerable.Range(0, bcdNum.Length).Where(x => x % 2 == 0).Select(x => Convert.ToByte(bcdNum.Substring(x, 2), 16)).ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM