Bitwise NOT

Well, we’re now onto the final of the four bitwise operators – bitwise NOT – probably the most simple of the four to understand.

Bitwise NOT is represented by the tilde symbol, ~, and only takes one operand.

Can I see an example?

~125 = 130

What is this actually doing?

Bitwise NOT essentially flips the bit setting for each bit, resulting in what is known as the “one’s complement” of the original number.

So the example above has a bit output as follows:

01111101    // 125
10000010    // 130

What would I use bitwise NOT for?

Turning off an individual bit

Actually, the NOT operator doesn’t itself turn off a bit, but in conjunction with the AND operator, you can use it with a mask to turn off a bit in a nice readable manner.

This is best illustrated with a full example:

char settings = 0;    // 00000000
char FLAG1 = 1;    // 00000001

Let’s assume that ‘settings’ is a byte we use to represent 8 boolean values. First of all, we’ll set the first bit of our settings variable to 1 using the OR operator and our FLAG1 mask:

settings = settings | FLAG1;

In binary this is:

00000000    // 0
00000001    // 1

If we want to turn that bit off again, instead of using AND and defining a new mask (11111110), we can use our FLAG1 mask and the NOT operator as follows:

settings = settings & ~FLAG1;

This reads quite intuitively: settings AND NOT FLAG1 turns off the first bit in settings. In binary:

00000001    // 1
11111110    // 254
00000000    // 0 – back to our original number

Note that applying the NOT operator to the flag generates the same binary sequence we would need to define as a new mask if we wanted to use AND alone (11111110). The NOT operator saves us a variable.

Can’t I just use XOR to turn this bit on and off?

Well spotted, yes you can!

settings = settings ^ FLAG1 // turns first bit on or off

The difference with XOR is a) you may not know if you are turning the bit on or off without checking the result (or input) as it’s just a switch, and b) XOR always has an effect, whether you intend it to or not.

With AND NOT you know you are explicitly turning a bit off, and if the bit is already off when you apply the mask, the result is unchanged.

Next week we’ll take a look at bit-shifting and summarise what we’ve covered with the four bitwise operators.

One Comment

  1. Posted 30 March 2012 at 17:47 | Permalink

    Thanks for the “What would I use this for?” section. Helped take the abstract concept and make it something more useful for me.