标准ANSI C函数函数介绍
读取16进制字符串函数:strtol
_CRTIMP long __cdecl strtol(const char *, char **, int); // stdlib.h
void HexStrToBinary(BYTE* data, int buf_len, const char * hex_str)
{
char * pHex = (char *)hex_str;
BYTE * pBuf = data;
int len = 0;
while(pHex && pHex[0] && pHex[1] && (len++ < buf_len))
{
*pBuf++ = (char)strtol(pHex, &pHex, 16);
}
*pBuf = '/0';
}
void BinaryToHexStr(char * hex_str, const BYTE* data, int len)
{
char * pHex = (char *)hex_str;
const byte * pData = data;
for (int i = 0; i < len; ++i)
{
sprintf(pHex, "%02x ", (byte)(*pData));
pData ++;
pHex += 3;
}
*pHex = '/0';
}
上述方法适合从文件里面读入一大串16进制字符串数据的转换,
如果数量很少而且是已知的,也可以这样转换:
如果数量很少而且是已知的,也可以这样转换:
char * pStr = "5E 34
int n[3] = {0};
sscanf(pStr, "%x %x %x", &n[0], &n[1], &n[2]);
_CRTIMP long __cdecl strtol(const char *, char **, int); // stdlib.h
void HexStrToBinary(BYTE* data, int buf_len, const char * hex_str)
{
char * pHex = (char *)hex_str;
BYTE * pBuf = data;
int len = 0;
while(pHex && pHex[0] && pHex[1] && (len++ < buf_len))
{
*pBuf++ = (char)strtol(pHex, &pHex, 16);
}
*pBuf = '/0';
}
void BinaryToHexStr(char * hex_str, const BYTE* data, int len)
{
char * pHex = (char *)hex_str;
const byte * pData = data;
for (int i = 0; i < len; ++i)
{
sprintf(pHex, "%02x ", (byte)(*pData));
pData ++;
pHex += 3;
}
*pHex = '/0';
}
上述方法适合从文件里面读入一大串16进制字符串数据的转换,
如果数量很少而且是已知的,也可以这样转换:
char * pStr = "5E 34
int n[3] = {0};
sscanf(pStr, "%x %x %x", &n[0], &n[1], &n[2]);
本文地址:http://www.45fan.com/dnjc/68929.html