Monday, October 4, 2010

BIT Hacks

Write a single line of code for the below operations

1. Set the nth bit to 1.
x = x | (1 << n);

2. Reset the nth bit of number
x = x & ~(1 << n);

3. Toggle the nth bit of the number.
x = x ^ (1 << n);

4. Convert the (right adjusted) n-bit field of x that begins at position p x =(x >> (p+1-n)) & ~(~0 << n);

An important point to note is that none of your operation should overflow the variable in use.

2 comments :

  1. //Let i be the number and we want to set the nth
    // bit. Assuming n<32 (for a 32-bit machine).

    i^=(1<<n);

    ReplyDelete
  2. @devil_fish ... ur code will flip the nth bit of i...
    to set the bit to 1 .. i |= (1<<n);
    to set the bit to 0 .. i &= ~(1<<n);

    Cheers

    ReplyDelete