Some Bitwise Operations in C

Some Bitwise Operations in C just for practise.

1. Even or Odd?

if ((x & 1) == 0) {
  //x is even
}
else {
  //x is odd
}

2. Isolate the rightmost 0 bit.

y = ~x & (x+1)

3. Isolate the rightmost 1 bit.

y = x & (-x)

4. Test if the n-th bit is set.

if (x & (1<<n)) {
   //n-th bit is set 
} else {
   //n-th bit is not set 
} 

5. Number of 1 bits in unsigned integer.

int number_of_ones(unsigned int x) {
   int total_ones = 0;
   while (x != 0) {
     x = x & (x-1);
     total_ones++;
   }   return total_ones;
} 

6. Reverse bits of an unsigned integer.

typedef unsigned int uint;
uint swapBits(uint x, uint i, uint j) {
   uint lo = ((x >> i) & 1);
   uint hi = ((x >> j) & 1);
   if (lo ^ hi) {
     x ^= ((1U << i) | (1U << j));
   }
   return x;
}

uint reverseXor(uint x) {
   uint n = sizeof(x) * 8;
   for (uint i = 0; i < n/2; i++) {
      x = swapBits(x, i, n-i-1);
   }
   return x;
}

7. Right propagate the rightmost 1-bit.

y = x | (x-1)

8. Set the n-th bit.

y = x | (1<<n)

9. Set the n-th bit.

y = x | (1<<n)

10. Unset the n-th bit.

y = x & ~(1<<n)

11. Swap bitwise.

// XOR
void swap(int *x, int *y)
{
    *x = *x ^ *y;
    *y = *x ^ *y;
    *x = *x ^ *y;
}

12. Toggle the n-th bit.

y = x ^ (1<<n)

13. Toggle the n-th bit.

y = x ^ (1<<n)

14. Turn off the rightmost 0 bit.

y = x | (x+1)

15. Turn off the rightmost 1 bit.

y = x & (x-1)
Advertisements