先取数据地址,转换成单字节长度的类型(unsigned char)的指针,然后按照十六进制逐字节打印即可,格式为“%.2x”。
sizeof()函数获取数据的字节数。
1 /* $begin show-bytes */
2 #include <stdio.h>
3 /* $end show-bytes */
4 #include <stdlib.h>
5 #include <string.h>
6 /* $begin show-bytes */
7
8 typedef unsigned char *byte_pointer; 9
10 void show_bytes(byte_pointer start, int len) { 11 int i; 12 for (i = 0; i < len; i++) 13 printf(" %.2x", start[i]); //line:data:show_bytes_printf
14 printf("\n"); 15 } 16
17 void show_int(int x) { 18 show_bytes((byte_pointer) &x, sizeof(int)); //line:data:show_bytes_amp1
19 } 20
21 void show_float(float x) { 22 show_bytes((byte_pointer) &x, sizeof(float)); //line:data:show_bytes_amp2
23 } 24
25 void show_pointer(void *x) { 26 show_bytes((byte_pointer) &x, sizeof(void *)); //line:data:show_bytes_amp3
27 } 28 /* $end show-bytes */
例子1:
1 /* $begin test-show-bytes */
2 void test_show_bytes(int val) { 3 int ival = val; 4 float fval = (float) ival; 5 int *pval = &ival; 6 show_int(ival); 7 show_float(fval); 8 show_pointer(pval); 9 } 10 /* $end test-show-bytes */
输入 12345,其十六进制表示为:0x 00 00 30 90,在64位windows cygwin64环境下,运行结果如下:
$ ./a.exe 12345 calling test_show_bytes 39 30 00 00
00 e4 40 46 ac cb ff ff 00 00 00 00
从结果中可以看到,在此环境下,int和float类型占用4字节,指针占用8字节,并且此机器的字节顺序为从数据低位到高位,即小端法机器。
例子2:
1 void string_ueg() { 2 /* $begin show-ustring */
3 const char *s = "ABCDEF"; 4 show_bytes((byte_pointer) s, strlen(s) + 1); 5 /* $end show-ustring */
6 } 7
8 void string_leg() { 9 /* $begin show-lstring */
10 const char *s = "abcdef"; 11 show_bytes((byte_pointer) s, strlen(s) + 1); 12 /* $end show-lstring */
13 }
结果:
Calling string_ueg 41 42 43 44 45 46 00 Calling string_leg 61 62 63 64 65 66 00
C语言中,字符串编码为一个以null(值为0)字符结尾的字符数组,代码中我在字符长度上加了1,以打印出这个尾巴;
另外,每个字符的编码这里是ASCII编码。
注: ascii字符码表在linux环境下可以用命令 man ascii调出。
代码来源: CSAPP附带代码文件show-bytes.c。