Friday, January 17, 2014

Toggle a specified bit in a bit string without effecting other bits

For example, we have a bit string 0111 and you have to turn the left most bit on 0 -> 1. How can we do that? We'll use XOR (^), left shift operation (<<) and the 0001 (1) bit string.
  1. Shift the 1 bit of 0001 to the position of the bit you want to change. In our example, we need to toggle the 3th bit (first bit is at position 0, that's why our target is at 3rd position not 4th). Thus, we shift 0001 to the left by 3. 0001 << 3 = 1000.
  2. Lastly, we XOR our bit string with the helper bit string. So, we have 0111 ^ 1000 = 1111
The general formula is:
bit_string = bit_string ^ (1 << positionOfBitToToggle)

0 comments:

Post a Comment