printf hex msg

static void hexdump (FILE *fp, const char *name, const void *ptr, size_t len) {
	const char *p = (const char *)ptr;
	size_t of = 0;

	if (name)
		fprintf(fp, "%s hexdump (%zd bytes):\n", name, len);

	for (of = 0 ; of < len ; of += 16) {
		char hexen[16*3+1];
		char charen[16+1];
		int hof = 0;

		int cof = 0;
		int i;

		for (i = of ; i < (int)of + 16 && i < (int)len ; i++) {
			hof += sprintf(hexen+hof, "%02x ", p[i] & 0xff);
			cof += sprintf(charen+cof, "%c",
				       isprint((int)p[i]) ? p[i] : '.');
		}
		fprintf(fp, "%08zx: %-48s %-16s\n",
			of, hexen, charen);
	}
}

example:
hexdump(stdout, "Message Payload", msg_buf, msg_len);

result:
------------------------------------------------
00000000: 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31  1111111111111111
00000010: 31 31 31                                                                   111                             
------------------------------------------------

 

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