来源 :https://www.chenxublog.com/2020/03/08/c-fast-convert-hex-char-array.html
HEX
方法最佳,讨论到最后变成哪种方法效率最优了。毕竟这代码是要在MCU上面跑的,要同时考虑到时间和空间的最优解。char str[] = '12345';
char data[] = {1,2,3,4,5,0xff};
'313233343500'
'0102030405FF'
0-16
对应0-F
即可:const char hex_table[] = {
'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
};
void to_hex(char *s, int l, char *d)
{
while(l--)
{
*(d+2*l+1) = hex_table[(*(s+l))&0x0f];
*(d+2*l) = hex_table[(*(s+l))>>4];
}
}
#include <stdio.h>
const char hex_table[] = {
'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
};
void to_hex(char *s, int l, char *d)
{
while(l--)
{
*(d+2*l+1) = hex_table[(*(s+l))&0x0f];
*(d+2*l) = hex_table[(*(s+l))>>4];
}
}
int main () {
char s[]= '1234';
char d[9];
d[8] = '\0';
to_hex(s,4,d);
printf('%s',d);
return 0;
}
31323334
'AAbb2fFF'
的量转成{0xAA,0xBB,0x2F,0xff}
这样的结果0-9
对应了0x30-0x39
A-F
对应了0x41-0x46
a-f
对应了0x61-0x66
0x39
,那它一定是字母;同时,在上面的分析也可以发现,如果这个字符是字母,不论大写小写,只需要看低四位就可以直接判断这个字符代表的数是多少
0x39
9
即为所需结果
void from_hex(char *s, int l, char *d)
{
while(l--)
{
char* p = s+l;
char* p2 = p-1;
*(d+l/2) =
( (*p>'9'? *p+9 : *p) & 0x0f ) |
( (*p2>'9'? *p2+9 : *p2) << 4 );
l--;
}
}
#include <stdio.h>
void from_hex(char *s, int l, char *d)
{
while(l--)
{
char* p = s+l;
char* p2 = p-1;
*(d+l/2) =
( (*p>'9'? *p+9 : *p) & 0x0f ) |
( (*p2>'9'? *p2+9 : *p2) << 4 );
l--;
}
}
int main () {
char s[]= '6F6B6f6b';
char d[5];
d[4] = '\0';
from_hex(s,8,d);
printf('%s',d);
return 0;
}
okok
联系客服