1. bitXor
/*
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));
}
思路:
2.tmin
* tmin - return minimum two's complement integer
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 4
* Rating: 1
*/
int tmin(void) {
int a = 1; //000000....1
return a << 31; //10000000.....
3.isTmax
/*
* 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+1)) ^ x)) & (!!(x+1) ^ 0x0);
}
思路:
max : a = 01111111111
min : a+1=1000000000
~(a+1) = 01111111111
a ^ (~(a+1)) == 0 ? 1 : 0
排除特殊情况:
a = 1111111111
a+1=0000000000
4. allOddBits
/*
* 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 A = 0xA;
int AA = A | (A << 4);
int AAAA = AA | (AA << 8);
int mask = AAAA | (AAAA << 16);
return !((x & mask) ^ mask);
标签:csapp,return,ops,int,Max,allOddBits,lab1,Legal,data
From: https://blog.csdn.net/catchmewhenifall/article/details/141190490