【c语言】数组转换成字符串,并按16进制格式打印

数组无法直接使用 printf 打印,一般会使用 for 循环逐个字节打印出来。
而我使用 ESP_LOG时,因为该日志打印系统自带了换行,打印出来的效果是每行一个字节,跟需求效果不同,所以这里采用一种把数组转换成字符串再打印的方法。

#include <stdio.h>
#include <string.h>
#include <malloc.h>

#define	IntToASCII(c)	(c)>9?((c)+0x37):((c)+0x30);

/**
  * @brief  数组转换成字符串,并按16进制格式打印 0x12, 0x34, 0x56, 0x78	 ->  12 34 56 78
  * @param 	inbuf:	输入数组
  * @param 	len:	输入数组的长度
  * @param 	outbuf:	输出字符串
  * @author	PJW
  */
void ArrayToHexString(const unsigned char *inbuf, int len, char *outbuf)
{
	char temp;
	int i = 0;

	for (i = 0; i < len; i++) {
		temp = inbuf[i]&0xf0;
		outbuf[3 * i + 0] = IntToASCII(temp>>4);
		temp = inbuf[i]&0x0f;
		outbuf[3 * i + 1] = IntToASCII(temp);
		/* space */
		outbuf[3 * i + 2] = 0x20;
	}

	outbuf[3 * i] = 0;
}

int main()
{
	unsigned char in[]={0x12,0x34,0x56,0x78};
    char* out = (char *) malloc(sizeof(in)*4);
    
    ArrayToHexString(in, sizeof(in), out);
  	printf("The output string : %s", out);  
    free(out); 
	return 0;
}

执行结果:
在这里插入图片描述

参考:数组转换成字符串,并按16进制格式打印


版权声明:本文为p1279030826原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。