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

本文深入探讨了C语言中底层数据操作、内存布局、数据结构实现及优化策略,包括字节操作、小端存储判断、数据位移等关键技术点。详细解析了如何通过位操作和数据类型转换实现数据的高效处理,并介绍了如何在不同场景下选择合适的内存布局以提升程序性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


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 - 8);
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原有的正负信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值