回复 12 楼 wp231957
//二进制转十六进制
char *bin2hex(const char *pBinIN, int len, char *pHexOUT)
{
int i = 0, j = 0, k = 0;
char *pBin = NULL, *p = NULL, *pTmp = NULL;
char *p3 = NULL;
int lenof4 = 0, len_Bin = 0;
//长度为4的倍数
lenof4 = len % 4;
if (lenof4 == 0)
{
len_Bin = len;
}
else
{
len_Bin = len + 4 - lenof4;
}
//分配内存
pBin = (char *)malloc(len_Bin + 1);
pTmp = (char *)malloc(5);
p3 = pTmp;
memset(pBin, '0', len_Bin + 1);
memset(pTmp, '0', 5);
//连接传入的二进制数,补齐为4的倍数
if (lenof4 == 0)
{
*pBin = '\0';
}
else
{
//最左侧长度<4补0
pBin[4 - lenof4] = '\0';
}
strncat(pBin, pBinIN, len);
printf("补齐的二进制数为:%s\n", pBin);
//查表得到十六进制数
for (i = 0; i < len_Bin;)
{
//得到4个二进制数pTmp
p = pBin + i;
strncpy(pTmp, p, 4);
pTmp += 4;
*pTmp = '\0';
pTmp = p3;
//查十六进制-二进制表,得到下标j
for (j = 0; j < 16; j++, p4++)
{
if (strcmp(*p4, pTmp) == 0)
{
//根据下标j查十六进制表得一个十六进制数
pHexOUT[k++] = tblDec_Hex[j];
break;
}
}
i = i + 4;
}
//字符串补上结束标志
pHexOUT[k] = '\0';
//释放内存
if (pBin != NULL)
{
free(pBin);
pBin = NULL;
}
if (pTmp != NULL)
{
free(pTmp);
pTmp = NULL;
}
return pHexOUT;
}
恩恩,还有一个问题麻烦您,这个是我调用的子程序, //根据下标j查十六进制表得一个十六进制数
pHexOUT[k++] = tblDec_Hex[j];
这一行,我想把tblDec_Hex[j];用指针替代。不用数组的形式,前面的定义是 static const char *tblDec_Hex = "0123456789ABCDEF";怎么定义一个指针指向他的首地址??