Search code examples
xor

Bitwise XOR: Setting X bit


I am a little confused about how to go about solving this one.

I read somewhere that

n ^ (1 << x)

Will solve it. Can I get to see a diagrammatic explanation of how this works?


Solution

  • Assuming we work with 8 bit number First you start with 1

    which would look like this in binary

    00000001
    

    then use the << operator to shift the bits of the operand by x bit

    if x = 4

    00001000 ( 16 in decimal, 0x10 in hexadecimal )
    

    then use the ^ operator (xor) with the resulting operand

    input n=8 ( 00000100)

    result

         00000100
    xor  00001000
      =  00001100
    

    PS: xor would flip the bit not set it, if you want to set it whatever the initial state, use the or operator (|)