Skip to content

Bitwise XOR

    Check out my free resources and deep-dive courses.

    free the mallocs mug gift

    A little something I made

    When I’m not writing about code, I design geeky mugs. If you’d like one for your desk, or know someone who would, take a look at my designs.

    Bitwise AND
    Bitwise NOT
    Bitwise OR
    Bit Shifting
    Bitwise RGBA Values

    Tip: Download my FREE Bitwise Guide PDF for a complete summary of this series of posts.

    Today we’ll look at the third out of four bitwise operators – bitwise XOR.

    Bitwise XOR is represented by the symbol ^ and is an exclusive OR operation.

    Can I see an example?

    130 ^ 10 = 136

    What is this actually doing?

    Bitwise XOR compares each bit setting and if either one is set, sets the corresponding output bit to 1. However, if both bits are set, then the corresponding output bit is set to zero.

    So to clarify, both OR and XOR compare each bit setting and if either one is set, sets the corresponding output bit to 1. However, if both bits are set, OR sets the output to 1, while XOR sets the output to zero.

    In short, XOR gives a result of 1 only if the two inputs are different.

    So the example above has bit comparisons as follows:

    10000010    // 130
    00001010    // 10
    ________
    10001000    // 136

    What would I use bitwise XOR for?

    Let’s take a look at how we might use XOR.

    Toggling with XOR

    XOR is primarily used to toggle bits on and off. Let’s say we have a byte which represents 8 boolean values and we want to turn the first two off and on again. We can use the same mask to toggle the bits we are interested in if we use the XOR operator.

    10000111    // 135
    00000011    // 3
    ________
    10000100    // 132

    Applying the mask turns off the last two bits.

    10000100    // 132
    00000011    // 3
    ________
    10000111    //135

    Applying it again turns the bits back on.

    All the other bits remain unchanged. XOR is just like applying a switch – very useful in low-level programming.

    Next week we’ll take a look at bitwise NOT. Have fun!

    Leave a Reply

    Your email address will not be published. Required fields are marked *