# O.2 — Bitwise operators

The bitwise operators

C++ provides 6 bit manipulation operators, often called bitwise operators:

Operator Symbol Form Operation
left shift << x << y all bits in x shifted left y bits
right shift >> x >> y all bits in x shifted right y bits
bitwise NOT ~ ~x all bits in x flipped
bitwise AND & x & y each bit in x AND each bit in y
bitwise OR | x | y each bit in x OR each bit in y
bitwise XOR ^ x ^ y each bit in x XOR each bit in y

Author's note

In the following examples, we will largely be working with 4-bit binary values. This is for the sake of convenience and keeping the examples simple. In actual programs, the number of bits used is based on the size of the object (e.g. a 2 byte object would store 16 bits).

For readability, we’ll also omit the 0b suffix outside of code examples (e.g. instead of 0b0101, we’ll just use 0101).

Bitwise left shift (<<) and bitwise right shift (>>) operators

The bitwise left shift (<<) operator shifts bits to the left. The left operand is the expression to shift the bits of, and the right operator is an integer number of bits to shift left by.

So when we say `x << 1`, we are saying "shift the bits in the variable x left by 1 place". New bits shifted in from the right side receive the value 0.

0011 << 1 is 0110
0011 << 2 is 1100
0011 << 3 is 1000

Note that in the third case, we shifted a bit off the end of the number! Bits that are shifted off the end of the binary number are lost forever.

The bitwise right shift (>>) operator shifts bits to the right.

1100 >> 1 is 0110
1100 >> 2 is 0011
1100 >> 3 is 0001

Note that in the third case we shifted a bit off the right end of the number, so it is lost.

Here's an example of doing some bit shifting:

This prints:

```1100
0110
1000
```

Note that the results of applying the bitwise shift operators to a signed integer are compiler dependent prior to C++20.

Warning

Prior to C++20, don't shift a signed integer (and even then, it's probably still better to use unsigned)

What!? Aren't operator<< and operator>> used for input and output?

They sure are.

Programs today typically do not make much use of the bitwise left and right shift operators to shift bits. Rather, you tend to see the bitwise left shift operator used with std::cout to output text. Consider the following program:

This program prints:

```1000
```

In the above program, how does operator<< know to shift bits in one case and output x in another case? The answer is that std::cout has overloaded (provided an alternate definition for) operator<< that does console output rather than bit shifting.

When the compiler sees that the left operand of operator<< is std::cout, it knows that it should call the version of operator<< that std::cout overloaded to do output. If the left operand some other type, then operator<< knows it should do its usual bit-shifting behavior.

The same applies for operator>>.

Note that if you're using operator << for both output and left shift, parenthisization is required:

This prints:

```01101
1100
```

The first line prints the value of x (0110), and then the literal 1. The second line prints the value of x left-shifted by 1 (1100).

Bitwise NOT

The bitwise NOT operator (~) is perhaps the easiest to understand of all the bitwise operators. It simply flips each bit from a 0 to a 1, or vice versa. Note that the result of a bitwise NOT is dependent on what size your data type is.

Flipping 4 bits:
~0100 is 1011

Flipping 8 bits:
~0000 0100 is 1111 1011

In both the 4-bit and 8-bit cases, we start with the same number (binary 0100 is the same as 0000 0100 in the same way that decimal 7 is the same as 07), but we end up with a different result.

We can see this in action in the following program:

This prints:
1011 11111011

Bitwise OR

Bitwise OR (|) works much like its logical OR counterpart. However, instead of applying the OR to the operands to produce a single result, bitwise OR applies to each bit! For example, consider the expression `0b0101 | 0b0110`.

To do (any) bitwise operations, it is easiest to line the two operands up like this:

```0 1 0 1
0 1 1 0
```

and then apply the operation to each column of bits.

If you remember, logical OR evaluates to true (1) if either the left, right, or both operands are true (1), and 0 otherwise. Bitwise OR evaluates to 1 if either the left, right, or both bits are 1, and 0 otherwise. Consequently, the expression evaluates like this:

```0 1 0 1
0 1 1 0
-------
0 1 1 1
```

Our result is 0111 binary.

This prints:

```0111
```

We can do the same thing to compound OR expressions, such as `0b0111 | 0b011 | 0b0001`. If any of the bits in a column are 1, the result of that column is 1.

```0 1 1 1
0 0 1 1
0 0 0 1
--------
0 1 1 1
```

Here's code for the above:

This prints:

```0111
```

Bitwise AND

Bitwise AND (&) works similarly to the above. Logical AND evaluates to true if both the left and right operand evaluate to true. Bitwise AND evaluates to true (1) if both bits in the column are 1. Consider the expression `0b0101 & 0b0110`. Lining each of the bits up and applying an AND operation to each column of bits:

```0 1 0 1
0 1 1 0
--------
0 1 0 0
```

This prints:

```0100
```

Similarly, we can do the same thing to compound AND expressions, such as `0b0001 & 0b0011 & 0b0111`. If all of the bits in a column are 1, the result of that column is 1.

```0 0 0 1
0 0 1 1
0 1 1 1
--------
0 0 0 1
```

This prints:

```0001
```

Bitwise XOR

The last operator is the bitwise XOR (^), also known as exclusive or.

When evaluating two operands, XOR evaluates to true (1) if one and only one of its operands is true (1). If neither or both are true, it evaluates to 0. Consider the expression `0b0110 ^ 0b0011`:

```0 1 1 0
0 0 1 1
-------
0 1 0 1
```

It is also possible to evaluate compound XOR expression column style, such as `0b0001 ^ 0b0011 ^ 0b01111`. If there are an even number of 1 bits in a column, the result is 0. If there are an odd number of 1 bits in a column, the result is 1.

```0 0 0 1
0 0 1 1
0 1 1 1
--------
0 1 0 1
```

Bitwise assignment operators

Similar to the arithmetic assignment operators, C++ provides bitwise assignment operators in order to facilitate easy modification of variables.

Operator Symbol Form Operation
Left shift assignment <<= x <<= y Shift x left by y bits
Right shift assignment >>= x >>= y Shift x right by y bits
Bitwise OR assignment |= x |= y Assign x | y to x
Bitwise AND assignment &= x &= y Assign x & y to x
Bitwise XOR assignment ^= x ^= y Assign x ^ y to x

For example, instead of writing `x = x >> 1;`, you can write `x >>= 1;`.

This program prints:

```0010
```

Summary

Summarizing how to evaluate bitwise operations utilizing the column method:

When evaluating bitwise OR, if any bit in a column is 1, the result for that column is 1.
When evaluating bitwise AND, if all bits in a column are 1, the result for that column is 1.
When evaluating bitwise XOR, if there are an odd number of 1 bits in a column, the result for that column is 1.

In the next lesson, we'll explore how these operators can be used in conjunction with bit masks to facilitate bit manipulation.

Quiz time

Question #1

a) What does 0110 >> 2 evaluate to in binary?

Show Solution

b) What does the following evaluate to in binary: 0011 | 0101?

Show Solution

c) What does the following evaluate to in binary: 0011 & 0101?

Show Solution

d) What does the following evaluate to in binary (0011 | 0101) & 1001?

Show Solution

Question #2

A bitwise rotation is like a bitwise shift, except that any bits shifted off one end are added back to the other end. For example 0b1001 << 1 would be 0b0010, but a left rotate by 1 would result in 0b0011 instead. Implement a function that does a left rotate on a std::bitset<4>. For this one, it's okay to use std::bitset<4>::test() and std::bitset<4>::set().

The following code should execute:

and print the following:

```0010
0011
```

Show Solution

 O.3 -- Bit manipulation with bitwise operators and bit masks Index O.1 -- Bit flags and bit manipulation via std::bitset

### 44 comments to O.2 — Bitwise operators

• Rob

So if
14 >> 1 = 1110 => 0111 = 7 = 14/2^1
16 >> 2 = 10000=>00100 = 4 = 16/2^2
24 >> 3 = 11000=>00011 = 3 = 24/2^3
Then so long as bits aren't lost off the end the bit shifting operators also work to either multiply or divide by 2 raised to the power of the amount of bits shifted by

I assume this is never recommended but just the way that stuff works in any base

• Alex

While you can multiple or divide by 2 by shifting bits, it isn't recommended that you do this manually. It's better to be clear about your intent, and then let the compiler handle the optimization of this for you.

• andy mackeroon

I came across exactly what we had been learning in this lesson over the week-end, when I looked up how to turn off the tool tip in windows. There was some discussion about it on a forum and someone had came across an entry in the registry, using flags set in hex, exactly like Alex had show us, but the guy had added the caveat that it look awfully complicated and should probably be left alone. I could see straight away that bit 7 needed to be turned off to switch off the tool tips. The number was a 2 byte hex number, and using the calculator that comes with Windows in programmer mode and hex number system, it also shows you the number in binary underneath the hex, so I was able to share with the forum the number in hex that the mask needed to be changed to to turn off the feature and felt very pleased with myself, lol.

• Walid Amin

Sorry but i think this sentence has a little mistake "If the left operand is an integer type, then operator<< knows it should do its usual bit-shifting behavior."

As an example:

it will output 23 (no shift left occured)

but if you want to do shift left you can do this:

Thank you

• Alex

The sentence is correct.

In the following code snippet, operator << evaluates from left to right. So this code:

cout<<2 evaluates first, printing 2, and then then cout<<3 evaluates, printing 3. Putting parenthesis changes the precedence, so (2<<3) evaluates first, causing this to do a bit shift and then print the value.

• Sind

~x - flips all the bits of int x.
Then, is there any option to flip a particular bit of the integer?

• Alex

Yes, the bitwise exclusive OR operator (operator^) can flip a particular bit.

e.g. myflags ^ 0x10; // flip the second to last bit

• evan

hi Alex

how are you doing. hope fine. you are doing a great job.

I have two questions,

a) myflags ^|0x10; you wrote in your reply above,   please can you explain, ^|, also which bit was flipped(is it the binary of 0x10)

b) if you want to toggle 2 bit states, why is it - myflags ^= option4 | option5; and not myflags ^= option4 ^ option5;

cheers

• Alex

1) Typo. I've updated the comment.

2) If you want to toggle 2 bit states, myflags ^= option4 | option5 evaluates as myflags ^= (option4 | option5), where (option4 | option5) turn bit flags 4 and 5 on. Then those are xor'd with myflags. Makes sense logically, right?

myflags ^= option4 ^ option5 will evaluate to myflags ^= 0, because (option4 ^ option5) evaluates to (1 ^ 1) which is 0. Definitely not what you want.

• mandeep

could anyone sove this program for meplzzzzzzzz

Bitwise example, run it and print out the results, reprogram it using OOP (c++)
concepts

#include
main ()
{
unsigned char x = '11';
unsigned char y = '27';
cout << "x = " << oct << short(x) << '\n';
cout << "y = " << oct << short(y) << '\n';
cout << "~x = " << oct << (short)(~x) << '\n';
cout << "x & y = " << oct << (short)(x & y) << '\n';
cout << "x | y = " << oct << (short)(x | y) << '\n';
cout << "x ^ y = " << oct << (short)(x ^ y) << '\n';
cout << "x << 2 = " << oct << (short)(x << 2) << '\n';
cout <> 2 = " << oct <> 2) << '\n';

• ghnat2013

• ghnat2013

Which of the following statements will display "Problem!" if bit 2 of flags is a '0'?
Answer if ((flags & 0x04) == 0x04) cout << "Problem!";
if ((flags & 0x04) != 0x04) cout << "Problem!";
if ((flags ^ 0x04) == 0x04) cout << "Problem!";
if ((flags ^ 0x04) != 0x04) cout << "Problem!";

2 points

• ghnat2013

To turn bit 3 of a variable to 0. the correct way is to:
Answer set the mask to 0xEF and peform the bitwise AND operation with the variable.
set the mask to 0xF7 and peform the bitwise AND operation with the variable.
set the mask to 0xEF and peform the bitwise OR operation with the variable.
set the mask to 0xF7 and peform the bitwise OR operation with the variable.