先取數據地址,轉換成單字節長度的類型(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。