CS:APP 第三版 第二章家庭作业

这篇博客详细解答了计算机科学与应用(CS:APP)第三版第二章的家庭作业,涵盖了2.64至2.80的全部题目,包括计算机体系结构的基础概念和计算问题。
摘要由CSDN通过智能技术生成

2.64

int any_odd_one(unsigned x){
	unsigned msk=0x55555555;
	return (x&msk)!=0;
}

2.65

int odd_one(unsigned x){
	int b1=1;
	int b2=2;
	int b3=4;
	int b4=8;
	int b5=16;
	x=(x>>b1)^x;
	x=(x>>b2)^x;
	x=(x>>b3)^x;
	x=(x>>b4)^x;
	x=(x>>b5)^x;
	return (x&1)!=0;
}

2.66

int leftmost_one(unsigned x) {
    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
    x |= x >> 16;
    x ^= x >> 1;
    return x;
}

2.68

int lower_one_mask(int n){
	unsigned ans=(unsigned)-1;
	size_t x=sizeof(int)<<3;
	return (int)((ans<<(x-n))>>(x-n));
}

2.70

int fits_bits(int x,int n){
	n-=1;
	return ((x>>n)==-1)||((x>>n)==0);
}

2.73

int saturating_add(int x, int y) {
    int z, f1, f2, ans, wd;
    wd = (sizeof(int) << 3) - 1;
    z = x + y;
    f1 = ((x >> wd) && (y >> wd) && ~(z >> wd)) || (~(x >> wd) && ~(y >> wd) && (z >> wd));
    f2 = (z >> wd) != 0;
    ans = z ^ ((1 << wd) - f2);
    ans = ans & (0 - f1);
    ans = ans ^ z;
    return ans;
}

2.74

int tsub_ok(int x,int y){
	int z=x-y;
	return !(~(x >> wd) && (y >> wd) && (z >> wd)) || ((x >> wd) && ~(y >> wd) && ~(z >> wd));
}

2.79

int mul3div4(int x){
	return (x+(x<<1))>>2;
}

2.80

int threefourths(int x){
	size_t w=sizeof(int)<<3;
	w=w-1;
	unsigned fl=~(x>>w);
	int tmp=x+(fl&3);
	w=w-1;
	fl=fl<<w;
	tmp=(tmp>>2)^fl;
	//printf("#%x %x\n",tmp,fl);
	return x-tmp;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值