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 else 14 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 }