标题:
求一个byte与hex相互转换的函数C语言
[打印本页]
作者:
zhengaohui
时间:
2018-12-7 13:06
标题:
求一个byte与hex相互转换的函数C语言
求一个byte与hex相互转换的函数C语言
作者:
bucker
时间:
2018-12-7 19:01
byte类型的数据本身就是八位二进制的,如果你想转为字符串的话有两种方法
方法1
unsigned char a;
unsigned char b;
unsigned char c;
a = 0xMN; // M表示高位,N表示低位
b = a >> 4; //b获得a的高位数据
c = a & 0x0F; //c获得a的低位数据
如果希望得到ASCII码,则
b = (b > 9) ? b+'0'+7 : b+'0';
c = (c > 9) ? c+'0'+7 : c+'0';
方法2
include "stdio.h"
unsigned char a;
char buf[10];
a = 0xMN; // M表示高位,N表示低位
sprintf(buf,"%02X",a); // buf数组的前两字节分别为M和N的ASCII字符。
作者:
略略略137
时间:
2018-12-7 19:45
public static byte[] Hex2Byte(string byteStr)
{
try
{
byteStr = byteStr.ToUpper().Replace(" ", "");
int len = byteStr.Length / 2;
byte[] data = new byte[len];
for (int i = 0; i < len; i++)
{
data[i] = Convert.ToByte(byteStr.Substring(i * 2, 2), 16);
}
return data;
}
catch (Exception ex)
{}
}
public string ByteToHexString( byte[] bytes)
{
StringBuilder sb = new StringBuilder();
if (bytes != null || bytes.Length > 0)
{
foreach (var item in bytes)
{
sb.Append(item.ToString("x2"));
}
}
return sb.ToString();
}
欢迎光临 (http://www.51hei.com/bbs/)
Powered by Discuz! X3.1