CSAPP data Lab
注意,本文代码出于节省括号避免繁杂的考虑,对运算符优先级利用得比较充分,比如 1>>n+1 等价于 1>>(n+1),所以代码里写了1>>n+1。
bitAnd
/*
* bitAnd - x&y using only ~ and |
* Example: bitAnd(6, 5) = 4
* Legal ops: ~ |
* Max ops: 8
* Rating: 1
*/
int bitAnd(int x, int y) {
return ~(~x|~y);
}
思路
- 德摩根定律
getByte
/*
* getByte - Extract byte n from word x
* Bytes numbered from 0 (LSB) to 3 (MSB)
* Examples: getByte(0x12345678,1) = 0x56
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 6
* Rating: 2
*/
int getByte(int x, int n) {
int bias = n<<3;
return (x>>bias)&0xFF;
}
思路
- 移位到最低的1byte然后用0xFF提取
logicalShift
/*
* logicalShift - shift x to the right by n, using a logical shift
i
* Can assume that 0 <= n <= 31
* Examples: logicalShift(0x87654321,4) = 0x08765432
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 20
* Rating: 3
*/
int logicalShift(int x, int n) {
return (1<<32+~n<<1)+~0 & (x>>n);
//equal to ((1<<31-n<<1)-1)&(x>>n);
//负号优先级高于移位
}
思路
因为不能用
-
,所以用取反加一代替取负构造低
32-n
bit的1来提取移位后的数值因为移位量不能小于0或大于等于32,所以对于n可能是0而导致移位量是32的情况,先移位31位,再移位1位
小技巧,如果n移位k,k ∈ [0, 32],则可以
n>>(k-!!k)>>!!k
bitCount
/*
* bitCount - returns count of number of 1's in word
* Examples: bitCount(5) = 2, bitCount(7) = 3
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 40
* Rating: 4
*/
int bitCount(int x) {
int mark1 =