Posts

bitwise programming is fun

A collection of examples of bitwise operations Turning a positive number into negative int negate(int x) {   return ~(x)+1; } Stripping off last set bit int strip_last_set_bit(int x) {      return x & (x-1); } Lowest bit set int lowest_set_bit(int x) {     return x & (-x); } Number of bits set int num_bits_set(int x) {     int i = 0;     while(x) {         x = x & (x - 1);         i++;     }     return i; } Rightmost bit set double log2(double x) {     return log(x) / log(2); } int rightmost_bit_set(int x) {     return log2(x & -x) + 1; } Rightmost bit unset  int rightmost_bit_unset(int x) {     if (x == 0)         return 1;         if ((x & (x + 1)) == 0)         return -1;...