CSAPP家庭作業(第二章)

來源:互聯網
上載者:User

標籤:eof   移位   temp   typedef   src   http   pointer   color   span   

2.55(*)

#include <stdio.h>typedef unsigned char *byte_pointer;void show_bytes(byte_pointer start,size_t len){    size_t 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 *));}int main(){    int ival=12345;    float fval=(float)ival;    int *pval=&ival;    show_int(ival);    show_float(fval);    show_pointer(pval);}

編譯並運行範例程式碼:

答:由此可見我的機器是採用低位先輸出的小端法機器。

 

2.56 -2.57 :略

 

2.58(**)

 1 #include <stdio.h> 2  3 typedef unsigned char *byte_pointer; 4  5  6 int is_little_endian(){ 7     int val=0x00000001; 8     byte_pointer valp=(byte_pointer)&val; 9     int temp;10     temp = valp[0];11     if(temp==1)12         return 1;13     else14         return 0;15 }16 17 void main(){18     is_little_endian();19 }

 

2.59(**)

C運算式:(x & 0xFF)|(y & ~0xFF)

 

2.60(**)

1 #include <stdio.h>2 3 unsigned replace_byte(unsigned x,int i,unsigned char b){4     return (x&(~(0xFF<<(i<<3))))|(b<<(i<<3));5 } 6 7 int main(){8     printf("%X\n",replace_byte(0x12345678,2,0xAB));9 }

(PS:這裡要求不能用乘法,為了實現8*i,也是用移位來實現乘法,其他的沒什麼痛點。)

 

2.61(**)

A:!~x;

B:!x;

C:!((~x)&0xFF);

D:!(x>>((sizeof(int)-1)<<3))

 

2.62(***)

1 #include <stdio.h>2 3 int int_shifts_are_arithmetic(){4     return !~(-1>>(sizeof(int)<<3));5 }6 7 int main(){8     printf("%d\n",int_shifts_are_arithmetic());9 }

這一題我沒有用==和!=運算,其實是可以用的。

 

2.63(***)

 

 1 unsigned srl(unsigned x,int k){ 2     unsigned xsra=(int)x>>k; 3     int w=8*sizeof(int); 4     unsigned z=2<<(w-k-1); 5     return xsra&(z-1); 6 } 7  8 int sra(int x,int k){ 9     int xsrl=(unsigned)x>>k;10     int w=8*sizeof(int);11     unsigned z=1<<(w-k-1);12     unsigned mask=z-1;13     unsigned right=mask&xsrl;14     unsigned left = ~mask&(~(z&xsrl)+z);15     return left|right;16 }

 

CSAPP家庭作業(第二章)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.