isAsciiDigit
/*
* isAsciiDigit - return 1 if 0x30 <= x <= 0x39 (ASCII codes for characters '0' to '9')
* Example: isAsciiDigit(0x35) = 1.
* isAsciiDigit(0x3a) = 0.
* isAsciiDigit(0x05) = 0.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 15
* Rating: 3
*/
int isAsciiDigit(int x) {
return (!((x + ~48 + 1) >> 31) & (!!((x + ~58 + 1) >> 31))) ;
}
anyEvenBit
/*
* anyEvenBit - return 1 if any even-numbered bit in word set to 1
* Examples anyEvenBit(0xA) = 0, anyEvenBit(0xE) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 12
* Rating: 2
*/
int anyEvenBit(int x) {
return !!((x & 0x55) | (x & (0x55 << 8)) | (x & (0x55 << 16)) | (x & (0x55 << 24)));
}
copyLSB
/*
* copyLSB - set all bits of result to least significant bit of x
* Example: copyLSB(5) = 0xFFFFFFFF, copyLSB(6) = 0x00000000
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int copyLSB(int x) {
return (x & 0x1)<< 31 >> 31;
}
leastBitPos
/*
* leastBitPos - return a mask that marks the position of the
* least significant 1 bit. If x == 0, return 0
* Example: leastBitPos(96) = 0x20
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 6
* Rating: 2
*/
int leastBitPos(int x) {
return (~x + 1) & x;
}
divpwr2
/*
* divpwr2 - Compute x/(2^n), for 0 <= n <= 30
* Round toward zero
* Examples: divpwr2(15,1) = 7, divpwr2(-33,4) = -2
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 15
* Rating: 2
*/
int divpwr2(int x, int n) {
int bias_virtual = (1 << n) + ~0; // 2^n - 1
int bias_real = (x >> 31) & bias_virtual;//negetive: 2^n - 1, else : 0
// num & -1 == num; num & 0 == 0;
return (x + bias_real) >> n;
}
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 count, mask1, mask2, mask3, mask4, mask5;
mask1=(0x55) | (0x55 << 8);
mask1 = (mask1) | (mask1 << 16); //mask1 = 0101 0101....
mask2 = (0x33) | (0x33 << 8);
mask2 = (mask2) | (mask2 << 16); //mask2 = 0011 0011....
mask3 = (0x0f) | (0x0f << 8);
mask3 = (mask3) | (mask3 << 16);//mask3 = 00001111 00001111....
mask4 = (0xff) | (0xff <<16); //mask4 = 00000000 11111111 00000000 11111111
mask5 = (0xff) | (0xff << 8); //mask5 = 00000000 00000000 11111111 11111111
count = (x & mask1) + ((x >> 1) &mask1);
count = (count & mask2) + ((count >> 2) & mask2);
count = (count & mask3) + ((count >> 4) & mask3);
count = (count & mask4) + ((count >> 8) & mask4);
count = (count & mask5) + ((count >> 16) & mask5);
return count;
}
更多推荐
深入理解计算机系统 dataLab
发布评论