Wednesday, January 1, 2014

Toggle a bit.

Toggling a bit will mean changing a bit to 0 if it was originally 1 or changing a bit to 1 it was originally 0.

Suppose you have been given a bit pattern and you want to toggle all the bit in the pattern. How can you achieve it.

Simple XOR it with 1's equal to number of bits given

For example, toggle (1101 0101 01)--> 0010 1010 10

           1101 0101 01
XOR     1111 1111  11   
---------------------------
           0010 1010 10

Toggling the Nth bit of a bit pattern can be achieved by left shifting 1  (N-1) times and XORing it with the bit pattern

For example, change the toogle the 4th bit (from left) in 1010 1000
N=4
N-1=3

i=(1<<3);
1010 1000 XOR i

1= 0000 0001
i=1<<4 = 0000 1000

          1010 1000
XOR    0000 1000
-----------------------
           1010 0000

Simply
get n;
after_toggle = given_bit_pattern ^ (1<<(n-1));





No comments:

Post a Comment