本文章适用场景:
#include int main(void)
{
printf("\tmain enter \n");
char* test1[128] = {0x11,0x22,0x33,0x44,0x55};
printf("111 test1: %s\n",test1);
printf("222 test1: %.2x %.2x %.2x %.2x %.2x\n", test1[0],test1[1],test1[2],test1[3],test1[4]);
return 0;
}
编译命令:gcc test.c -o test
编译后执行结果:
我们发现自己数组test1无法用%s方式打印,如果想把字节数组转发为字符串可以用%s方式输出,利用如下代码即可。
话不多说贴代码:
int main(void)
{
unsigned char src[6] = { 0x12, 0x00, 0x56, 0x78, 0x90, 0xab };
char s[13] = { 0 }; //注意字符串申请的空间,以防越界,无论使用实体数组还是动态申请malloc方式,空间应该为字节数组长度*2+1
int i;
char c1, c2;
for (i = 0; i < 6; i++)
{
c1 = src[i] & 0xFu;
c2 = (src[i] >> 4) & 0xFu;
sprintf(s + i * 2, "%x%x", c2, c1);
}
printf("!! %s\n",s);
printf("len %d\n",strlen(s));
return 0;
}
//1200567890ab