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;
   
    return rightmost_bit_set(~x);  
}

Num with only a range of bits set

unsigned int set_range_of_bits(unsigned int l, unsigned int r)
{
    return  ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);
}


Huge fun to be continued


Comments