1 实验说明
从CSAPP课程主页下载datalab实验所需的压缩包。下图说明本次实验需要补齐的函数名列表。
2 实验
2.1
/*
* bitXor - x^y using only ~ and &
* Example: bitXor(4, 5) = 1
* Legal ops: ~ &
* Max ops: 14
* Rating: 1
*/
int bitXor(int x, int y) {
return ~(~(~x & y)& ~(x & ~y));
}
解题思路:
利用a⊕b = (¬a ∧ b) ∨ (a ∧¬b)公式和德-摩根定律得到上面的代码.
2.2
/*
* tmin - return minimum two's complement integer
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 4
* Rating: 1
*/
int tmin(void) {
return 0x1<<31;
}
解题思路:
首先明确32位整数最小值的二进制为0x80000000.
2.3
/*
* isTmax - returns 1 if x is the maximum, two's complement number,
* and 0 otherwise
* Legal ops: ! ~ & ^ | +
* Max ops: 10
* Rating: 1
*/
int isTmax(int x) {
int res = !((~(x+1))^x) & !!(~x);
return res ;
}
解题思路:
首先明确32位整形最大值为0x7fffffff.由于题目中规定不能使用移位符号,
2.4
/*
* allOddBits - return 1 if all odd-numbered bits in word set to 1
* where bits are numbered from 0 (least significant) to 31 (most significant)
* Examples allOddBits(0xFFFFFFFD) = 0, allOddBits(0xAAAAAAAA) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 12
* Rating: 2
*/
int allOddBits(int x) {
int mask = 0xAA | (0xAA<<8) | (0xAA<<16) | (0xAA <<24);
x = x & mask;
return !~(x>>1 | x);
}
解题思路:
首先要获取奇数位的信息,则有mask:0xAAAAAAAA.(十六进制A的二进制表示为1010).当奇数位全为1时,(x>>1 | x)则表示0xffffffff,反之,则不成立.
2.5
/*
* negate - return -x
* Example: negate(1) = -1.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int negate(int x) {
return</