这两个函数分别用于将字节数组转换为十六进制字符串和将十六进制字符串转换为字节数组。让我为您详细介绍这两个函数。
ByteToHexStr
函数:
cppCopy codevoid ByteToHexStr(const unsigned char *source, unsigned char *dest, int sourceLen)
{在这里插入代码片
unsigned char highByte, lowByte;
for (int i = 0; i < sourceLen; i++)
{
highByte = source[i] >> 4;
lowByte = source[i] & 0x0f;
highByte += 0x30;
if (highByte > 0x39)
dest[i * 2] = highByte + 0x07;
else
dest[i * 2] = highByte;
lowByte += 0x30;
if (lowByte > 0x39)
dest[i * 2 + 1] = lowByte + 0x07;
else
dest[i * 2 + 1] = lowByte;
}
}
介绍:
source
:输入的字节数组。dest
:存储输出的十六进制字符串的缓冲区。sourceLen
:输入字节数组的长度。
用法:
cppCopy codeunsigned char inputBytes[] = {0xAB, 0xCD, 0xEF, 0x12};
unsigned char hexString[2 * sizeof(inputBytes) + 1]; // 2倍字节数 + 1(字符串结束符)
ByteToHexStr(inputBytes, hexString, sizeof(inputBytes));
// 现在 hexString 包含十六进制字符串表示的字节数组
HexStrToByte
函数:
cppCopy codevoid HexStrToByte(const unsigned char *source, unsigned char *dest, int sourceLen)
{
unsigned char highByte, lowByte;
for (int i = 0; i < sourceLen; i += 2)
{
highByte = toupper(source[i]);
lowByte = toupper(source[i + 1]);
if (highByte > 0x39)
highByte -= 0x37;
else
highByte -= 0x30;
if (lowByte > 0x39)
lowByte -= 0x37;
else
lowByte -= 0x30;
dest[i / 2] = (highByte << 4) | lowByte;
}
}
介绍:
source
:输入的十六进制字符串。dest
:存储输出的字节数组的缓冲区。sourceLen
:输入十六进制字符串的长度。
用法:
cppCopy codeconst unsigned char *hexString = "ABCDEF12";
unsigned char outputBytes[sizeof(hexString) / 2];
HexStrToByte(hexString, outputBytes, sizeof(hexString));
// 现在 outputBytes 包含十六进制字符串解析出的字节数组
注意:这两个函数假设输入的十六进制字符串是有效的,并且没有进行输入的合法性检查。在实际使用中,可能需要增加适当的错误检查和边界处理来确保程序的健壮性。