數組轉換成字符串,並按16進制格式打印

  如數組內容:

		uint8_t buf[] = {0x23, 0x45, 0x98, 0x16}:

  打印出如下格式:

		23 45 98 16

  可使用如下代碼轉換,將數組的每個成員一個個轉換成ASC II碼:

/*
 *	@param1		buf:輸入數組
 *	@param2		len:輸入數組的長度
 *	@param3		out:輸出的字符串
 */
void ArrayToHexString(const char *buf, int len, char *out)
{
#define	IntToASCII(c)	(c)>9?((c)+0x37):((c)+0x30);

	char temp;
	int i = 0;

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

	out[3 * i] = 0;

}

  例:

int main()
{
	char buf[50];
	char out[200];
	for (int i = 0; i < 50; i++){
		buf[i] = i;
	}

	ArrayToHexString(buf, 50, out);

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

	return 0;
}

原數組爲:0 1 2… 49,   結果爲:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章