在C#中将int转换为十六进制的字节 [英] Convert int to byte as HEX in C#

查看:1371
本文介绍了在C#中将int转换为十六进制的字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过串行将十六进制字符串发送到设备,我现在是这样的:

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

现在我需要将类似30的int值转换为 c [1 ] = 0x30 或int值34给出 c [1] = 0x34
我希望你明白我的意思。

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.

那我该怎么办呢?

推荐答案

此格式称为 二进制编码的十进制 。对于两位数,将整数除以10,然后乘以16,然后将除法的余数除以10:

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#中将int转换为十六进制的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆