将字符串转换成16进制数
比如一组32个字符的,如4c8c6827f05dbc64b1c43e7e343d9adc4c8c6827f05dbc64b1c43e7e343d9adc
,字符串。
字符串的内容为0~f
,如果以字符的形式写到flash里面,占用32个字节大小
转成十六进制的话,占用一半大小,即16个字节。
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
/*
// C prototype : void StrToHex(unsigned char *pbDest, unsigned char *pbSrc, int nLen)
// parameter(s): [OUT] pbDest - 输出缓冲区
// [IN] pbSrc - 字符串
// [IN] nLen - 16进制数的字节数(字符串的长度/2)
// return value:
// remarks : 将字符串转化为16进制数
*/
void StrToHex(unsigned char *pbDest, unsigned char *pbSrc, int nLen)
{
char h1,h2;
unsigned char s1,s2;
int i;
for (i=0; i<nLen; i++)
{
h1 = pbSrc[2*i];
h2 = pbSrc[2*i+1];
s1 = toupper(h1) - 0x30; //十六进制 0x30 , dec十进制 48 , 图形 0
if (s1 > 9)
s1 -= 7;
s2 = toupper(h2) - 0x30;
if (s2 > 9)
s2 -= 7;
pbDest[i] = s1*16 + s2;
}
}
int main()
{
unsigned char tmp[65] = "4c8c6827f05dbc64b1c43e7e343d9adc4c8c6827f05dbc64b1c43e7e343d9adc";
unsigned char out[32] = {0};
memset(out, 0 ,sizeof(out));
printf("sizeof(out):%ld\n", sizeof(out));
printf("tmp:%s\n", tmp);
StrToHex(out, tmp, 32);
int i;
for(i=0; i<sizeof(out); i++)
{
printf("out[%2d] : %2x ", i, out[i]);
if ((i + 1) % 8 == 0)
{
printf("\r\n");
}
}
return 0;
}
结果:
linbo@linbo-ThinkPad-T490:~/test$ gcc string.c
linbo@linbo-ThinkPad-T490:~/test$ ./a.out
sizeof(out):32
tmp:4c8c6827f05dbc64b1c43e7e343d9adc4c8c6827f05dbc64b1c43e7e343d9adc
out[ 0] : 4c out[ 1] : 8c out[ 2] : 68 out[ 3] : 27 out[ 4] : f0 out[ 5] : 5d out[ 6] : bc out[ 7] : 64
out[ 8] : b1 out[ 9] : c4 out[10] : 3e out[11] : 7e out[12] : 34 out[13] : 3d out[14] : 9a out[15] : dc
out[16] : 4c out[17] : 8c out[18] : 68 out[19] : 27 out[20] : f0 out[21] : 5d out[22] : bc out[23] : 64
out[24] : b1 out[25] : c4 out[26] : 3e out[27] : 7e out[28] : 34 out[29] : 3d out[30] : 9a out[31] : dc
我们分析一波:
比如字符串4c8c6827f05dbc64b1c43e7e343d9adc4c8c6827f05dbc64b1c43e7e343d9adc
的前俩字符4c
char h1,h2;
h1 = 4,
h2 = c,
s1 = toupper(h1) - 0x30; //十六进制 0x30 (十进制48) , dec十进制 48 , 图形 0
,4是数字转成大写依旧为4,4的ascii的十进制为52
那么
s1 = 52 - 48 = 4;
s2 = 67 - 48 = 19;
当s2大于9,说明不是0~9的数字。
if (s2 > 9)
s2 -= 7;
s2 = s2 - 7 = 19 - 7 = 12
,结果等于12,如下图,红框,12的十六进制正好为0C
那么 pbDest[i] = s1*16 + s2;
就是4*16 + 12 = 76,即4C
参考
https://blog.csdn.net/weixin_38184741/article/details/90265734
https://blog.csdn.net/u013776495/article/details/51318031