您的位置:首页 > 移动开发

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

2019-09-20 19:18 1201 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/HolmiumJiang/article/details/101074596

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: