## Bitwise Operators – Free Guide

I have an exciting new eGuide available.

Most of this info is available in various places on my site, but I’ve collated it all together in one document, and updated it, so it’s easier for you to use.

What does it cover?

It’s a no-jargon guide to the four bitwise operators in C (AND, OR, XOR, NOT).

Not only does it walk you through exactly how each one works, with examples, it also provides explanations of how they would be used in programming and (as if that wasn’t enough), there’s a handy quick-start guide at the end which you can refer to so you know exactly when to use each operator and why.

It’s all written in a no-nonsense, easy to read format, that makes programming the joy it should be.

Hurrah to that, I say.

## Bitwise XOR

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.

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 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!