CSAPP datalab

119 阅读1分钟
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)));
}
/*
Score   Rating  Errors  Function
 1      1       0       bitXor
Total points: 1/1
*/
  • 按照异或的定义:x & ~y | ~x & y,然后把或用德摩根定律转成与非。

或者

  • 按照x,y不同时为0和1,~(~x & ~y) & ~(x & y)。
2. 求补码的最小值
/*
 * tmin - return minimum two's complement integer 
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 4
 *   Rating: 1
 */
int tmin(void) {
    return 0x1 << 31;
}
  • 题目说了假设是32位的机器,1左移31位即可
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) {
    return !((~x) ^ (x + 1)) & !!(x + 1);
}
  • 判断两个值相等用异或
  • 补码的最大值即0x7FFFFFFF,取反和加一相等
  • 发现-1,即0xFFFFFFFF也满足上述性质,将其排除
4. 对32位整数,编号为0~31位,所有奇数位为1返回1,否则返回0
/*
 * 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 << 8;
    mask += 0xAA;
    mask <<=8;
    mask += 0xAA;
    mask <<= 8;
    mask += 0xAA;
    return !((mask & x) ^ mask);
}
  • 先把掩码搞成0xAAAAAAAA可以省操作步骤
  • 最开始对x每次移8位,0xAA做掩码,每次的结果再与,会多很多操作步骤