1. 一个数的从右起第p1位和第p2位swap n位
1 unsigned int swapBits(unsigned int x, unsigned int p1, unsigned int p2, unsigned int n) { 2 unsigned int set1 = (x >> p1) & ((1 << n) - 1); 3 unsigned int set2 = (x >> p2) & ((1 << n) - 1); 4 unsigned int xored = set1 ^ set2; //same is 0, different is 1 5 xored = (xored << p1) | (xored << p2); 6 return x ^ xored; //anybit ^ 0 = anybit, anybit ^ 1 = !anybit, so same no need to change, different need to be changed 7 } 8 9 int main() 10 { 11 cout << swapBits(28, 0, 3, 2) << endl; 12 return 0; 13 }
2. Add two integer
1 int Add(int x, int y) { 2 while (y) { 3 int carry = x & y; 4 x = x ^ y; 5 y = carry << 1; 6 // cout << carry << " " << x << " " << y << endl; 7 } 8 return x; 9 }
3. min函数
1 int minnum(int x, int y) { 2 return y + ((x - y) & ((x - y) >> (sizeof(int) * 8 - 1))); 3 }
also can use division
4. count bit set in an integer
1 int countsetbits(int x) { 2 int ans = 0; 3 while(x) { 4 x &= (x-1); 5 ans++; 6 } 7 return ans; 8 }