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 prefix 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 operand 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:

1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <bitset> #include <iostream> int main() { std::bitset<4> x { 0b1100 }; std::cout << x << '\n'; std::cout << (x >> 1) << '\n'; // shift right by 1, yielding 0110 std::cout << (x << 1) << '\n'; // shift left by 1, yielding 1000 return 0; } |

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:

1 2 3 4 5 6 7 8 9 10 11 |
#include <bitset> #include <iostream> int main() { unsigned int x { 0b0100 }; x = x << 1; // use operator<< for left shift std::cout << std::bitset<4>{ x }; // use operator<< for output return 0; } |

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 is an integral 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, parenthesization is required:

1 2 3 4 5 6 7 8 9 10 11 12 |
#include <bitset> #include <iostream> int main() { std::bitset<4> x{ 0b0110 }; std::cout << x << 1 << '\n'; // print value of x (0110), then 1 std::cout << (x << 1) << '\n'; // print x left shifted by 1 (1100) return 0; } |

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).

We will talk more about operator overloading in a future section, including discussion of how to overload operators for your own purposes.

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:

1 2 3 4 5 6 7 8 9 |
#include <bitset> #include <iostream> int main() { std::cout << std::bitset<4>{ ~0b0100u } << ' ' << std::bitset<8>{ ~0b0100u }; return 0; } |

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 OR 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 OR 0 1 1 0 ------- 0 1 1 1

Our result is 0111 binary.

1 2 3 4 5 6 7 8 9 |
#include <bitset> #include <iostream> int main() { std::cout << (std::bitset<4>{ 0b0101 } | std::bitset<4>{ 0b0110 }); return 0; } |

This prints:

0111

We can do the same thing to compound OR expressions, such as `0b0111 | 0b0011 | 0b0001`

. If any of the bits in a column are *1*, the result of that column is *1*.

0 1 1 1 OR 0 0 1 1 OR 0 0 0 1 -------- 0 1 1 1

Here's code for the above:

1 2 3 4 5 6 7 8 9 |
#include <bitset> #include <iostream> int main() { std::cout << (std::bitset<4>{ 0b0111 } | std::bitset<4>{ 0b0011 } | std::bitset<4>{ 0b0001 }); return 0; } |

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 AND 0 1 1 0 -------- 0 1 0 0

1 2 3 4 5 6 7 8 9 |
#include <bitset> #include <iostream> int main() { std::cout << (std::bitset<4>{ 0b0101 } & std::bitset<4>{ 0b0110 }); return 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 AND 0 0 1 1 AND 0 1 1 1 -------- 0 0 0 1

1 2 3 4 5 6 7 8 9 |
#include <bitset> #include <iostream> int main() { std::cout << (std::bitset<4>{ 0b0001 } & std::bitset<4>{ 0b0011 } & std::bitset<4>{ 0b0111 }); return 0; } |

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 XOR 0 0 1 1 ------- 0 1 0 1

It is also possible to evaluate compound XOR expression column style, such as `0b0001 ^ 0b0011 ^ 0b0111`

. 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 XOR 0 0 1 1 XOR 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;`

.

1 2 3 4 5 6 7 8 9 10 11 |
#include <bitset> #include <iostream> int main() { std::bitset<4> bits { 0b0100 }; bits >>= 1; std::cout << bits; return 0; } |

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?

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

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

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

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:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <bitset> #include <iostream> // "rotl" stands for "rotate left" std::bitset<4> rotl(std::bitset<4> bits) { // Your code here } int main() { std::bitset<4> bits1{ 0b0001 }; std::cout << rotl(bits1) << '\n'; std::bitset<4> bits2{ 0b1001 }; std::cout << rotl(bits2) << '\n'; return 0; } |

and print the following:

0010 0011

O.3 -- Bit manipulation with bitwise operators and bit masks |

Index |

O.1 -- Bit flags and bit manipulation via std::bitset |

Hi!

I may be way off here but if I'm understanding correctly there may be a slight miscalculation in "Bitwise left shift (<<) and bitwise right shift (>>) operators".

The example says shifting 1 bit to the right yields 0110 but then shifting back to the left yields 1000. Shouldn't it be 1100?

Thanks!

Hi!

Are you talking about the very first snippet?

`x` doesn't get modified in this example.

I humbly apologise!

Thank you for clarifying that! :-)

Hello, I had learn from beginning lesson and read all comments until the struct part. A few months ago, I had see there is still updated in the bitwise lesson. So i had skipped and come back now. This is my first comment, I want to ask what is different used between the bitwise operator and bitwise assignment (example:: "<<" and "<<=", or ">>" and ">>=" )

I had trying bitwise assignment operator on the question 3 and get the different result

std::bitset<4> rotl(std::bitset<4> bits) {

return (bits <<= 1) | (bits >>= 3);

}

the output:

0000

0010

std::bitset<4> rotl(std::bitset<4> bits) {

return (bits << 1) | (bits >> 3);

}

Your output:

0010

0011

In `rotl`, you don't want to modify `bits`, so you need the non-assigning operators.

what the 'u' character here stand for ?

std::bitset<4>{ ~0b0100u }

"unsigned". Without it, the integer would be `signed` and turn into -5 when flipped.

Hi There,

Great site, really enjoying the lesson layout.

I came up with a different answer to Q3, which was based on only replacing the 'test' and 'set' operands in my code from Q2 with bitwise operators.. Can you please let me know if there's a reason why I should not do it the way I have? I like the simplicity of your answer, but don't know enough yet to tell if mine is 'wrong' for any reason... here's the code for my rotl function:

oh man, there was this brilliant method in comparison to my

num x 10

if num > 10000, num - 10000 + 1

Sorry to triple post but this was a really challenging lesson and I had to dig deep to figure it out. Can you explain why the solution to question 3 works the way it does? I've done the math on function rotl, and have verified to myself that it works. But how would a person come up with this solution when given this problem to solve? Thanks for any clarification you can provide.

For question 3, you are essentially working under the constraint to use only basic bitwise operators. As such, you cannot access a specific position of your bitset.

Now that we have set the environment in which we have to work, let's dig into the exercise.

The left shift is doing almost all the work that is asked from you, but it causes the leftmost bit value to be lost. "Before" applying left shift to your bitset, you have to come up with a solution for isolating the leftmost bit to save it.

You could come up with this kind of operation:

I leave up to you the verification of the results.

The issue now is to bring this isolated bit to the rightmost position of the left shift result (remember, the left shift is almost doing all the job).

You could take the result of the previous bitwise AND operation and apply a right shift to bring the isolated bit to the rightmost position:

But those two operations can be simplified if you think about how the shift operations cause bits to be lost and use it at your advantage. This way, the two previous code snippets can be simplified to:

After isolating the leftmost bit, you want to restore it to the result of the left shift operation at the rightmost position.

After applying the left shift to your initial bitset, your rightmost bit is 0. You have to find a bitwise operation that sets your backed up bit without altering the values of the other bits.

Two bitwise operators can achieve this: OR and XOR. The XOR operator is often considered as a more complex operator because it is theoretically written as a combination of AND and OR:

p XOR q = (p OR q) AND NOT(p AND q)

So you are better off sticking to the basic operator OR:

If you do not understand yet why the OR operator does the job, write down the possible results until you come to this conclusion:

"The logic operator OR aggregates information from its operands with priority to value 1. Similarly, the logic operator AND aggregates information from its operands with priority to value 0."

And as for every aggregation, you are bound to lose information. This is not a concern in our case for two reasons:

- the only information the right operand "leftmostBitBackup" holds is its rightmost bit,

- the righmost bit of the left shift result does not hold any information and is equal to 0 by definition.

When you strip down the previous code snippets from their intermediary definitions, you happen to program the solution you were seeking:

Note that the literal 0b1000 in the first code snippet and the expression (bits >> 3) in the final solution are elementary masks (cf. lesson O.3).

Thank you! I worked through this and understand bitset operators now. Appreciate your help with this, great explanation.

I came up with a novel approach to question 3. My reasoning is that rotl function will only ever shift a 1 from position 3 to position 0 if the value of the bitset number is 8 or higher. So I convert to an unsigned long, compare if the result of the conversion is higher than 8, and if so, flip bit position 0 to a 1 after the left shift. Otherwise the left shift is performed without the flip.

Hi! It appears you're missing #include <bitset> in the code for section "What!? Aren't operator<< and operator>> used for input and output?"

It would be helpful to add why is bitwise operations are so handy? Expecially bitwise shift?

after a bit (no pun intended) of fiddling I discovered that the value bits it's composed of 4 bits numbered 0, 1, 2, 3, and not 1, 2, 3, 4, my program crashed when I tried to display the bit number "4" with the test function.

anyways, here's my solution, to me it looks a different but totally valid alternative, but maybe it's not. can I improve it in some way?

Your formatting is misleading. Line 8 and 9 are not guarded by the `else`, they are executed unconditionally. Use your editor's auto-formatting feature.

Your logic is specialized to your test data. Try rotating `0010`.

Thank you very much for these lessons. You guys are truly awesome.

So for Question #3 I came up with this much more inefficient solution.

Hi nascardriver!

It's me again. Found another typo. In the beginning of the 2nd section "Bitwise left shift (<<) and bitwise right shift (>>) operators" there's a sentence that says: "The left operand is the expression to shift the bits of, and the right operator ...", should be "the right operand" instead of "operator".

Also wanted to give you a suggestion about the last two quizzes. You've used an abbreviation for function name "rotl" which I've seen you recommend against using them in the comments before. I think for this case maybe something like "rotateLeft" would be better, or maybe add a comment to clarify. You're the experts here, so I'll leave it up to you to decide.

The second thing that I found out about the quizzes is that the headers aren't sorted alphabetically as they should be according to the best practices.

The function is named "rotl" for historic reasons and uniformity with the standard library. I added a comment to the quiz and an explanation to the solution. If we were the first programmers to choose a name for this function, it shouldn't be abbreviated. Typos and includes fixed, thanks again for improving the lessons!

I see. Thanks for the reply.