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

This prints:


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


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:


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:

This prints:


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:

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.

This prints:


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:

This prints:


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

This prints:


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

This prints:


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

This program prints:



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 test() and set().

The following code should execute:

and print the following:


Show Solution

Question #3

Extra credit: Redo quiz #2 but don't use the test and set functions.

Show Solution

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

231 comments to O.2 — Bitwise operators

  • WhiskeyTaster

    My idea:

    Of course we can use {} after 'if' instead of ( , ) construction.

  • pinkunuko

    This is my answer. If you notice, the if() has curly braces but the else doesn't. For some reason, it won't compile if I don't put the curly braces around it, giving the error "expecting a statement"

    • KotoGP

      The reason it won't compile without the {} is because you are doing multiple statements when your if statement evaluates to true. If you return to the lesson that introduces the if statement (lesson 4.10) it mentions you can only have 1 statement in an if condition. there more info in lesson 7.2.

  • Armando IG

    Hello I was comparing my code to the answer in question #2 and I made a temporal variable to hold the input and don't risking changing the original variable, but in your answer you do manipulate the original input, does that change the variable value outside the function scope or is it safe to do as you did?

    I give you my code just in case

    • nascardriver

      Hello, `bits` is passed to `rotl()` by value. Parameters that are passed by value are copied. Modifying them inside of the function has no effect on the original variable.

  • Jordan

    Hi, is rotl in the Question #2 a user defined function?

  • frog

    my solution for quiz #3

  • Evelyn Ann Grace

    Hey ive made an odd / even number checker method using this beside using %2  i wonder which is faster, mod it by 2 or just checking the last bit in place?

    Is 1 An even number? No
    Is 2 An even number? Yes
    Is 3 An even number? No
    Is 4 An even number? Yes
    Is 5 An even number? No
    Is 6 An even number? Yes
    Is 7 An even number? No
    Is 8 An even number? Yes
    Is 9 An even number? No
    Is 10 An even number? Yes

    *turns out mod the value by 2 is faster (i %2)
    after looping 30.000x bit check took 10.3s and modulus operation took 7.2s

  • Hi

    My solution for #2 (I know this is somewhat bad practice, but I couldn't help making a one-liner)

  • Deva_B.D.M.

    this is my solution. for question #2

  • Hi

    What does the "u" mean in "std::bitset<4>{ ~0b0100u }"?

  • Hellstone

    Could someone explain me how chris solution works?

    • Josh

      Hi, so due to the parentheses we evaluate the first set of brackets first, then the second, then use bitwise OR on the results. For example, given 1001 as the argument:

      (bits<<1) evaluates first. 1001 is shifted 1 place to the left, resulting in the first operand to our bitwise OR being 0010.

      (bits>>3) evaluates next. 1001 is shifted 3 places to the right, resulting in the second operand to our bitwise OR being 0001.

      Our expression has so far evaluated to 0010 | 0001. We now perfrom bitwise OR with the two operands:

        0 0 1 0
        0 0 0 1
        0 0 1 1

      This gives us the result 0011.

  • abcdaf

    Why did we use const bool instead of bool on the second questions answer?

  • David

    So I tried to do question #3 and when I tried to execute my code, this happened:

    - It didn't compile, and I had this message: LINK : debug\XXXXX.exe not found or not built by the last incremental link; performing full link

    - Also, my antivirus caught my .exe file, so I thought that was the reason the linker was giving me this message. My antivirus told me that the virus was a GenericRxMx kind.

    - I withe listed my .exe file because honestly I didn't think that my file was doing something wrong (And I mistakenly thought to myself that because it was a file that I created then it wouldn't hurt my PC or something)

    - Next time I run the script, and then everything went nuts, all of my screens were blinking, and I couldn't even stop the execution, my console wasn't working, and I honestly thought that I did damage something in my PC memory because I just couldn't do anything but wait to hopefully finish the execution, and it did. Then I restarted my PC and from the beginning, (without even opening Visual Studio or executing the EXE) all of my screens went blinking again. I waited and then when I could, I deleted the .exe file and everything related to that project and after that I haven't had any problems anymore.

    The lines I wrote were something like this:

    - bits1 =  bits << 1
    - bits2 =  bits << 3
    - bits3 =  (bits1 | bits2)
    - bits4 =  (bits ^ bits3)
    - print value

    Sorry for the long comment, but my question is, can it be dangerous to play along with bit manipulations while learning because I really don't want to damage my PC or see what I saw after I executed my code.

  • tran duc phong

    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.

    • TomCruise

      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)

  • Michael Wycombe

    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.

    • Alex

      All integer operands are typically promoted to int, and padded with zeros if needed (see 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.

  • deerr

    int x{5};
    binary=0000 0000 0000 0101 (because int is 4bytes=32bits)
    When we use bitwise left or right shift
    x is now 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 :))

  • Raysen

    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

  • Waldo Lemmer

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

  • Istabi Tystab

    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.

    • nascardriver

      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.

  • Alex

    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 <<= 1;

        return bits;


    • nascardriver

      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.

  • yeokaiwei

    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

    (<<1) 0010 OR
    (>>3) 0001

    Is this the meaning of the rotatel?

  • jacob christie

    1st example seems wrong...
    why is 0110 shifted left once 1000, should not it be 1100?

Leave a Comment

Put all code inside code tags: [code]your code here[/code]