《CSAPP》讀書雜記 - Chapter 2. Representing and Manipulating Information

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.