`

深入理解计算机系统 (第二章家庭作业)

阅读更多
   如题,家庭作业。记录个人的部分答案,由于时间关系,不会每题都做。


   2.38:show_bytes()

   直接参照书本里面的程序:
#include <stdio.h>
#include <string.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){

  short int sval = val;
  int ival = sval;
  float fval = (float) ival;
  int *pval = &ival;
  show_int(ival);
  show_float(fval);
  show_pointer(pval);

}


main(){

  test_show_bytes(1);
  test_show_bytes(2);
  test_show_bytes(65535);
  test_show_bytes(65536);
  test_show_bytes(-1);

}


  2.41 判断机器是否为小端存储
  原理同上一题,设置一个能在一个byte里面表示的数值,然后提取小端的第一个byte。
#include <stdio.h>
typedef unsigned char *byte_pointer;

void is_little_endian(){
  int tval = 10;
  byte_pointer bp = (byte_pointer)&tval; 
  if((int)bp[0] == 10)
    printf("This is a little endian! \n");
  else
    printf("This is a large endian!\n");
}

main(){
  is_little_endian();
}


2.42题:将x左移,直至最后一个byte到最左边,然后右移直至整个byte回到最右边。为了防止这最后一个byte的最高位为1, 导致在右移过程中,高位补码均为1,要将x高位均置位为0:与127做&运算。y的处理比较简单,直接截取即可。

#include <stdio.h>

void combinex_y (int x, int y){
  unsigned int len, tempx;
  len = sizeof(x) * 8 ;
  tempx = x << (len -;
  tempx = tempx >> (len-8);
  tempx = tempx & 127;
  int tempy = ~127;
  tempy = tempy & y;
  printf("y except last byte: %.2x \n", tempy);
  printf("combined of x and y : %x \n\n" , tempx + tempy);
}

main(){
  int x = 0x89ABCDEF;
  int y = 0x76543210;
  combinex_y(x, y); 
}


2.44题: 思路,负值(-1)右移一位。
typedef unsigned char * byte_pointer;
void int_shift_are_arithmetic(){
  int x = -1;
  int shiftLen = 1;
  int shiftx = x >> shiftLen;
  if(shiftx != 0){
    printf("\n arithmetic shift! \n");
  }
  else
    printf("\n Not arithmetic shift!\n");
}

2.45题:当左移位数超过所定义数值类型的位数时,将会采用移动位数对数值位数求模后的值,作为移动的位数。为了避免这类问题,可以采用多步左移的方式:(下面只是思路,还需完善)
void bad_int_32(){
  int x = 1;
  int x_left_31 = x << 31;
  int x_left_32 = x_left_31 << 1;
  printf("\n number 1 shift left for 31 bit: %.2x \n" , x_left_31);
  printf("\n number 1 shift left for 32 bit: %.2x \n" , x_left_32);
}

2.46题:问题主要在于对byte进行int扩展时,补码的填充。直接采用(int)byte的方式,将会直接在高位补充0,而忽略掉byte原有的正负信息。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics