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 test() and 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 alex i really don't understand what you mean(A bitwise rotation is like a bitwise shift, except that any bits shifted off one end are added back to the other end)Can you give a more concrete example? Try putting the board in the direction of learning as you say and doing it step by step.

Bitwise rotation means the bits will return either from the right or left. For example 0b1001 << 1 would be 0b0010 right? Then where is the other 1? It is gone, So you have to make a function that can do a rotation with these bits, so it should be from 0b1001 shift to the left by 1, and the result is this 0b0011(So the number 1 after b goes back to the right)

All of the examples show a complete set of four (4) bits being ored or anded together. What happens if one operand is shorter than the other? I bring this up 'cause I came across some code that had the following test for 'oddness' - if (*p & 1) {//do something}. The clear implication is that the result of the '&' operation only extends for the distance of the shorter operand.

But what happens for if (*p ^ 1) {//do something}? I guess, again, the result will be one bit long and only true if the original bit is 0. This could stand in as a test for being even, with the RH bit being a 0 so the '^' (xor) would yield true only for even inputs.

Great site; lots of useful examples and insights. Many thanks for the hard work and accuracy.

Regards

MWycombe.

All integer operands are typically promoted to int, and padded with zeros if needed (see https://en.cppreference.com/w/cpp/language/operator_arithmetic for more info).

Much in the same way the decimal value 12 and 00000012 are the same number, 0011 and 0000 0000 0000 0011 are the same number.

int x{5};

decimal=5

binary=0000 0000 0000 0101 (because int is 4bytes=32bits)

When we use bitwise left or right shift

x=x>>1;

x is now 2

decimal=2

binary=0000 0000 0000 0010

We shifted one position above so the first bit which was 1 was discarded and a new zero was added at the last position,

retaining our data type size (4bytes).

We can shift according to our data type.

For an integer we can shift 31 positions then we go out of our memory where our x is stored and we can't do that.

My question is what is the operation that makes our "inserted bits" zero.

Is it a something in our compiler, what gives that instruction?

I really want to understand that.

Thank you.

good job with your tutorials(more examples,more quizzees :))

To my disappointed I discovered that some keyboard layouts (in my case the italian layout) do include the tilde symbol as a way to be typed in.

I think it would be helpful for others to add a note in the bitwise NOT part, that you can still input the ~ using the ASCII code ALT+126 on your numpad (referring to the codes in chapter 4.11).

Of course, my keyboard is also a compact type with no numpad :P

Good job, Chris! Your solution is much more elegant than mine:

Hi, my answer to question 2 was this:

The question is, is it better to use a bool to store just the last digit rather than declaring an auxiliary bitset?

P.S. Great site, I'm really enjoying following the lessons.

Copying something that you don't need a copy of is generally not good. For a 4-bit bitset, there's probably no difference compared to using a bool, but if the bitset is larger, a bool is better.

In question number 2 is it better to initialize a boolean value or is it fine to program the function rotl() like I did below?

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

{

if (bits.test(3))

{

bits <<= 1;

bits.set(0);

}

else

bits <<= 1;

return bits;

}

Using a `bool` prevents the repetition of `bits <<= 1`. This repetition isn't terrible, so your code is fine too, but you should strive to avoid repetitions.

1. The page doesn't explain what test() and set() are.

Perhaps, each function could link to the relevant explaination page like Wikipedia?

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

(<<1) 0010 OR

(>>3) 0000

0010

(<<1) 0010 OR

(>>3) 0001

0011

Is this the meaning of the rotatel?

test() and set() are explained in the previous lesson under "Manipulating bits via std::bitset".

1st example seems wrong...

why is 0110 shifted left once 1000, should not it be 1100?

0110 << 1 is 1100 I can't find what you're referring to in the lesson though

ctrl+f, then put in this

Here's an example of doing some bit shifting:

`x >> 1` doesn't modify `x`.

`x << 1` applies to `x`, which still has value 1100

OHHHHHH!!!!!!! i understand, its just printing it, sorry thats so obvious, my mistake, thanks!