猿问

如何在C中将字节数组转换为十六进制字符串?

我有:


uint8 buf[] = {0, 1, 10, 11};

我想将字节数组转换为字符串,以便可以使用printf打印该字符串:


printf("%s\n", str);

得到(不需要冒号):


"00:01:0A:0B"

任何帮助将不胜感激。


犯罪嫌疑人X
浏览 1018回答 3
3回答

慕码人2483693

printf("%02X:%02X:%02X:%02X", buf[0], buf[1], buf[2], buf[3]);以更通用的方式:int i;for (i = 0; i < x; i++){&nbsp; &nbsp; if (i > 0) printf(":");&nbsp; &nbsp; printf("%02X", buf[i]);}printf("\n");要连接到字符串,有几种方法可以执行此操作...我可能会保留一个指向字符串末尾的指针并使用sprintf。您还应该跟踪数组的大小,以确保其大小不会超过分配的空间:int i;char* buf2 = stringbuf;char* endofbuf = stringbuf + sizeof(stringbuf);for (i = 0; i < x; i++){&nbsp; &nbsp; /* i use 5 here since we are going to add at most&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;3 chars, need a space for the end '\n' and need&nbsp; &nbsp; &nbsp; &nbsp;a null terminator */&nbsp; &nbsp; if (buf2 + 5 < endofbuf)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (i > 0)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; buf2 += sprintf(buf2, ":");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; buf2 += sprintf(buf2, "%02X", buf[i]);&nbsp; &nbsp; }}buf2 += sprintf(buf2, "\n");

MMMHUHU

这是一种更快的方法:#include <stdlib.h>#include <stdio.h>unsigned char *&nbsp; &nbsp; &nbsp;bin_to_strhex(const unsigned char *bin, unsigned int binsz,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; unsigned char **result){&nbsp; unsigned char&nbsp; &nbsp; &nbsp;hex_str[]= "0123456789abcdef";&nbsp; unsigned int&nbsp; &nbsp; &nbsp; i;&nbsp; if (!(*result = (unsigned char *)malloc(binsz * 2 + 1)))&nbsp; &nbsp; return (NULL);&nbsp; (*result)[binsz * 2] = 0;&nbsp; if (!binsz)&nbsp; &nbsp; return (NULL);&nbsp; for (i = 0; i < binsz; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; (*result)[i * 2 + 0] = hex_str[(bin[i] >> 4) & 0x0F];&nbsp; &nbsp; &nbsp; (*result)[i * 2 + 1] = hex_str[(bin[i]&nbsp; &nbsp; &nbsp;) & 0x0F];&nbsp; &nbsp; }&nbsp; return (*result);}int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;main(){&nbsp; //the calling&nbsp; unsigned char&nbsp; &nbsp; &nbsp;buf[] = {0,1,10,11};&nbsp; unsigned char *&nbsp; &nbsp;result;&nbsp; printf("result : %s\n", bin_to_strhex((unsigned char *)buf, sizeof(buf), &result));&nbsp; free(result);&nbsp; return 0}
随时随地看视频慕课网APP
我要回答