打印数据的字节(十六进制)表示-c语言代码

  先取数据地址,转换成单字节长度的类型(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 /* $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字节,并且此机器的字节顺序为从数据低位到高位,即小端法机器。

代码来源: CSAPP附带代码文件show-bytes.c

猜你喜欢

转载自www.cnblogs.com/tlz888/p/10590163.html