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.
- 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.
- Lastly, we XOR our bit string with the helper bit string. So, we have 0111 ^ 1000 = 1111
bit_string = bit_string ^ (1 << positionOfBitToToggle)
0 comments:
Post a Comment