標籤:style blog color io ar for sp 資料 div
1.
代碼:
#include <stdio.h>typedef unsigned char *byte_pointer;void show_bytes(byte_pointer start, int len){ int i; for(i = 0; i < len; i++) { printf(" %.2x", start[i]); } printf("\n");}void show_int(int x){ show_bytes((byte_pointer)&x, sizeof(int));}void show_float(float x){ show_bytes((byte_pointer)&x, sizeof(float));}void show_pointer(void * x){ show_bytes((byte_pointer)&x, sizeof(void *));}void test_show_bytes(int val){ int ival = val; float fval = (float)ival; int *pval = &ival; printf(" %x\n", pval); show_int(ival); show_float(fval); show_pointer(pval);}int main(){ test_show_bytes(12345);}
運行結果:
56683c18 39 30 00 00 00 e4 40 46 18 3c 68 56 ff 7f 00 00
其中函數show_int()、show_float()的調用比較好理解。
show_int()中&x取到實際地址。為使擷取地址指向資料中每個位元組的內容,需要進行類型轉換,即把int *轉換成unsigned char *,但是類型轉換後已經不知道資料的長度,所以需要人工傳入資料長度的參數,即 sizeof(int)。此後,把每次指標指向的內容(unsigned char形式)以十六進位形式輸出。show_float()類似。
int *pval = &val 運行後,pval為指標,64位,其內容指向val的地址。printf(" %x\n", pval)是以十六進位形式輸出地址,但是由於 %x只能表示32位,所以去掉高32位,變成 56 68 3c 18,小端模式輸出後即為 18 3C 68 56
《CSAPP》讀書雜記 - Chapter 2. Representing and Manipulating Information