2019年9月14日
题目2.59
解法一:
(x & 0xFF) | (y & ~0xFF)
解法二:
(x | ~0xFF) & (y | 0xFF)
特殊要求
题目2.61
答案:
A: !(~x) 或 !(x+1)
B: !x
C: !((x & 0xFF) – 0xFF)
或 !(~x << ((sizeof(int) – 1) << 3))
D: !(x >> ((sizeof(int) – 1) << 3))
或 !(x & (0xFF << ((sizeof(int) – 1) << 3)))
题目2.63
答案:
/* 注意k=0的情况,不能左移w-k位*/
unsigned srl(unsigned x, int k){
/* Perform shift arithmetically */
unsigned xsra = (int) x >> k;
int w = sizeof(int) << 3;
int temp = (2 << (w - k - 1)) - 1;//最低的w-k位是1,高位是0
return xsra & temp;//高位变0
}
int sra(unsigned x, int k){
/* Perform shift logically */
int xsrl = (unsigned) x >> k;
int w = sizeof(int) << 3;
int sign = xsrl & (1 << (w - k - 1));//仅保留右移后的符号位
int temp = ~sign + 1;//符号位为0,则temp所有位为0;符号位为1,则temp的高k+1位为1,其余位为0
return xsrl | temp;//高位全部变符号位
}
助教学长还提供了一种特别简洁的sra()函数的写法
int sra(unsigned x, int k){
/* Perform shift logically */
int xsrl = (unsigned) x >> k;
int w = sizeof(int) << 3;
( x & (1<<(w-1)) ) && ( xsrl |= (~0<<(w-k)) );//A && B, 若A为真则执行B,若A为假则跳过B
return xsrl;
}
ics好难QUQ
加油!