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 |

When you were explaining operator overloading, you declared an unsigned integer x. We know that its size is 4 bytes i.e. 4*8 = 32 bits but you had used only 4 and even in the output, they were 4.

Leading zeroes aren't printed

Explain this and its reason a little bit further: "Note that the results of applying the bitwise shift operators to a signed integer are compiler dependent prior to C++20."

Before C++20, it was implementation-defined how signed integers were stored on a binary level. Most commonly, the most significant bit was used to store the sign (0 = positive, 1 = negative). If the number is negative, it also changed the meaning of the remaining bits. So if you shifted your signed integer such that the first bit becomes 1, the output depends on which negative number representation your compiler uses.

Since C++20, signed integers are stored in two's complement.

My solution with making use of ? operator.

Congrats to Chris. This was mine:

Crazy to think that my solution was basically Chris's, but with extra useless steps.

Hi! I'm just here to say that Chris' solution to question 3 was mind blowing.

mine was kind of cheating, as I just used flip(when the last bit is 0) instead of set!

Is this solution for the question#2 correct?

hello! why is needed the "u" when is used the Bitwise NOT(~). I searched a little and i find that is something called narrowing conversion, but the "u" has some relation with "unsigned"?

I have look at the solution. I will fix my code like you in time I wish

Hi, is it okey to do it this way, or does it fall in the side effect type of case ?

That's fine. `(bits << 1)` is always evaluated before `.set(0)`.

Maybe a typo: In Question #2, should "std::bitset<4>::test()" not rather be "std::bitset<4>.test()" (and likewise for the set() function)? If it is correct as is, it might not be clear to the reader what is meant here.

It was correct as written. That syntax is used to refer to member functions without an instance.

I updated the sentence to just say `test()` and `set()` without the type. It should be clear which functions are meant from the context.

In question 2 how can you write about test and setting when you first thought about it in the next chapter? I skipped this question because I did not understand it, arriving on the next chapter I found it. It’s a thing you do all across these lessons talking about things that are thought in future lessens and not even mentioning that it’s thought in a future lesson. (Some times you do mention and give a link)

`test` and `set` were shown in the previous lesson

Does not work, it gives this error:

./Playground/file0.cpp: In function 'int main()':

./Playground/file0.cpp:8:31: error: 'ob0001' was not declared in this scope

8 | std::cout << (std::bitset<4> {ob0001} ^ std:bitset<4> {ob0011} ^ std::bitset<4> {ob0111});

| ^~~~~~

./Playground/file0.cpp:8:37: error: no matching function for call to 'std::bitset<4>::bitset(<brace-enclosed initializer list>)'

8 | std::cout << (std::bitset<4> {ob0001} ^ std:bitset<4> {ob0011} ^ std::bitset<4> {ob0111});

| ^

In file included from ./Playground/file0.cpp:1:

../Playground/++/10.1.0/bitset:946:9: note: candidate: 'template<class _CharT> std::bitset<_Nb>::bitset(const _CharT*, typename std::__cxx11::basic_string<_CharT>::size_type, _CharT, _CharT) [with _CharT = _CharT; long unsigned int _Nb = 4]'

946 | bitset(const _CharT* __str,

| ^~~~~~

../Playground/++/10.1.0/bitset:946:9: note: template argument deduction/substitution failed:

../Playground/++/10.1.0/bitset:925:2: note: candidate: 'template<class _CharT, class _Traits, class _Alloc> std::bitset<_Nb>::bitset(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, std::size_t, std::size_t, _CharT, _CharT) [with _CharT = _CharT; _Traits = _Traits; _Alloc = _Alloc; long unsigned int _Nb = 4]'

925 | bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __s,

| ^~~~~~

../Playground/++/10.1.0/bitset:925:2: note: template argument deduction/substitution failed:

../Playground/++/10.1.0/bitset:914:2: note: candidate: 'template<class _CharT, class _Traits, class _Alloc> std::bitset<_Nb>::bitset(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, std::size_t, std::size_t) [with _CharT = _CharT; _Traits = _Traits; _Alloc = _Alloc; long unsigned int _Nb = 4]'

914 | bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __s,

| ^~~~~~

../Playground/++/10.1.0/bitset:914:2: note: template argument deduction/substitution failed:

../Playground/++/10.1.0/bitset:893:2: note: candidate: 'template<class _CharT, class _Traits, class _Alloc> std::bitset<_Nb>::bitset(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, std::size_t) [with _CharT = _CharT; _Traits = _Traits; _Alloc = _Alloc; long unsigned int _Nb = 4]'

893 | bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __s,

| ^~~~~~

../Playground/++/10.1.0/bitset:893:2: note: template argument deduction/substitution failed:

../Playground/++/10.1.0/bitset:874:17: note: candidate: 'constexpr std::bitset<_Nb>::bitset(long long unsigned int) [with long unsigned int _Nb = 4]'

874 | constexpr bitset(unsigned long long __val) noexcept

| ^~~~~~

../Playground/++/10.1.0/bitset:874:17: note: conversion of argument 1 would be ill-formed:

../Playground/++/10.1.0/bitset:869:26: note: candidate: 'constexpr std::bitset<_Nb>::bitset() [with long unsigned int _Nb = 4]'

869 | _GLIBCXX_CONSTEXPR bitset() _GLIBCXX_NOEXCEPT

| ^~~~~~

../Playground/++/10.1.0/bitset:869:26: note: candidate expects 0 arguments, 1 provided

../Playground/++/10.1.0/bitset:751:11: note: candidate: 'constexpr std::bitset<4>::bitset(const std::bitset<4>&)'

751 | class bitset

| ^~~~~~

../Playground/++/10.1.0/bitset:751:11: note: conversion of argument 1 would be ill-formed:

../Playground/++/10.1.0/bitset:751:11: note: candidate: 'constexpr std::bitset<4>::bitset(std::bitset<4>&&)'

../Playground/++/10.1.0/bitset:751:11: note: conversion of argument 1 would be ill-formed:

./Playground/file0.cpp:8:44: error: found ':' in nested-name-specifier, expected '::'

8 | std::cout << (std::bitset<4> {ob0001} ^ std:bitset<4> {ob0011} ^ std::bitset<4> {ob0111});

| ^

| ::

./Playground/file0.cpp:8:56: error: 'ob0011' was not declared in this scope

8 | std::cout << (std::bitset<4> {ob0001} ^ std:bitset<4> {ob0011} ^ std::bitset<4> {ob0111});

| ^~~~~~

./Playground/file0.cpp:8:62: error: no matching function for call to 'std::bitset<4>::bitset(<brace-enclosed initializer list>)'

8 | std::cout << (std::bitset<4> {ob0001} ^ std:bitset<4> {ob0011} ^ std::bitset<4> {ob0111});

| ^

In file included from ./Playground/file0.cpp:1:

../Playground/++/10.1.0/bitset:946:9: note: candidate: 'template<class _CharT> std::bitset<_Nb>::bitset(const _CharT*, typename std::__cxx11::basic_string<_CharT>::size_type, _CharT, _CharT) [with _CharT = _CharT; long unsigned int _Nb = 4]'

946 | bitset(const _CharT* __str,

| ^~~~~~

../Playground/++/10.1.0/bitset:946:9: note: template argument deduction/substitution failed:

../Playground/++/10.1.0/bitset:925:2: note: candidate: 'template<class _CharT, class _Traits, class _Alloc> std::bitset<_Nb>::bitset(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, std::size_t, std::size_t, _CharT, _CharT) [with _CharT = _CharT; _Traits = _Traits; _Alloc = _Alloc; long unsigned int _Nb = 4]'

925 | bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __s,

| ^~~~~~

../Playground/++/10.1.0/bitset:925:2: note: template argument deduction/substitution failed:

../Playground/++/10.1.0/bitset:914:2: note: candidate: 'template<class _CharT, class _Traits, class _Alloc> std::bitset<_Nb>::bitset(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, std::size_t, std::size_t) [with _CharT = _CharT; _Traits = _Traits; _Alloc = _Alloc; long unsigned int _Nb = 4]'

914 | bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __s,

| ^~~~~~

../Playground/++/10.1.0/bitset:914:2: note: template argument deduction/substitution failed:

../Playground/++/10.1.0/bitset:893:2: note: candidate: 'template<class _CharT, class _Traits, class _Alloc> std::bitset<_Nb>::bitset(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, std::size_t) [with _CharT = _CharT; _Traits = _Traits; _Alloc = _Alloc; long unsigned int _Nb = 4]'

893 | bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __s,

| ^~~~~~

../Playground/++/10.1.0/bitset:893:2: note: template argument deduction/substitution failed:

../Playground/++/10.1.0/bitset:874:17: note: candidate: 'constexpr std::bitset<_Nb>::bitset(long long unsigned int) [with long unsigned int _Nb = 4]'

874 | constexpr bitset(unsigned long long __val) noexcept

| ^~~~~~

../Playground/++/10.1.0/bitset:874:17: note: conversion of argument 1 would be ill-formed:

../Playground/++/10.1.0/bitset:869:26: note: candidate: 'constexpr std::bitset<_Nb>::bitset() [with long unsigned int _Nb = 4]'

869 | _GLIBCXX_CONSTEXPR bitset() _GLIBCXX_NOEXCEPT

| ^~~~~~

../Playground/++/10.1.0/bitset:869:26: note: candidate expects 0 arguments, 1 provided

../Playground/++/10.1.0/bitset:751:11: note: candidate: 'constexpr std::bitset<4>::bitset(const std::bitset<4>&)'

751 | class bitset

| ^~~~~~

../Playground/++/10.1.0/bitset:751:11: note: conversion of argument 1 would be ill-formed:

../Playground/++/10.1.0/bitset:751:11: note: candidate: 'constexpr std::bitset<4>::bitset(std::bitset<4>&&)'

../Playground/++/10.1.0/bitset:751:11: note: conversion of argument 1 would be ill-formed:

./Playground/file0.cpp:8:82: error: 'ob0111' was not declared in this scope

8 | std::cout << (std::bitset<4> {ob0001} ^ std:bitset<4> {ob0011} ^ std::bitset<4> {ob0111});

| ^~~~~~

./Playground/file0.cpp:8:88: error: no matching function for call to 'std::bitset<4>::bitset(<brace-enclosed initializer list>)'

8 | std::cout << (std::bitset<4> {ob0001} ^ std:bitset<4> {ob0011} ^ std::bitset<4> {ob0111});

| ^

In file included from ./Playground/file0.cpp:1:

../Playground/++/10.1.0/bitset:946:9: note: candidate: 'template<class _CharT> std::bitset<_Nb>::bitset(const _CharT*, typename std::__cxx11::basic_string<_CharT>::size_type, _CharT, _CharT) [with _CharT = _CharT; long unsigned int _Nb = 4]'

946 | bitset(const _CharT* __str,

| ^~~~~~

../Playground/++/10.1.0/bitset:946:9: note: template argument deduction/substitution failed:

../Playground/++/10.1.0/bitset:925:2: note: candidate: 'template<class _CharT, class _Traits, class _Alloc> std::bitset<_Nb>::bitset(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, std::size_t, std::size_t, _CharT, _CharT) [with _CharT = _CharT; _Traits = _Traits; _Alloc = _Alloc; long unsigned int _Nb = 4]'

925 | bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __s,

| ^~~~~~

../Playground/++/10.1.0/bitset:925:2: note: template argument deduction/substitution failed:

../Playground/++/10.1.0/bitset:914:2: note: candidate: 'template<class _CharT, class _Traits, class _Alloc> std::bitset<_Nb>::bitset(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, std::size_t, std::size_t) [with _CharT = _CharT; _Traits = _Traits; _Alloc = _Alloc; long unsigned int _Nb = 4]'

914 | bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __s,

| ^~~~~~

../Playground/++/10.1.0/bitset:914:2: note: template argument deduction/substitution failed:

../Playground/++/10.1.0/bitset:893:2: note: candidate: 'template<class _CharT, class _Traits, class _Alloc> std::bitset<_Nb>::bitset(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, std::size_t) [with _CharT = _CharT; _Traits = _Traits; _Alloc = _Alloc; long unsigned int _Nb = 4]'

893 | bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __s,

| ^~~~~~

../Playground/++/10.1.0/bitset:893:2: note: template argument deduction/substitution failed:

../Playground/++/10.1.0/bitset:874:17: note: candidate: 'constexpr std::bitset<_Nb>::bitset(long long unsigned int) [with long unsigned int _Nb = 4]'

874 | constexpr bitset(unsigned long long __val) noexcept

| ^~~~~~

../Playground/++/10.1.0/bitset:874:17: note: conversion of argument 1 would be ill-formed:

../Playground/++/10.1.0/bitset:869:26: note: candidate: 'constexpr std::bitset<_Nb>::bitset() [with long unsigned int _Nb = 4]'

869 | _GLIBCXX_CONSTEXPR bitset() _GLIBCXX_NOEXCEPT

| ^~~~~~

../Playground/++/10.1.0/bitset:869:26: note: candidate expects 0 arguments, 1 provided

../Playground/++/10.1.0/bitset:751:11: note: candidate: 'constexpr std::bitset<4>::bitset(const std::bitset<4>&)'

751 | class bitset

| ^~~~~~

../Playground/++/10.1.0/bitset:751:11: note: conversion of argument 1 would be ill-formed:

../Playground/++/10.1.0/bitset:751:11: note: candidate: 'constexpr std::bitset<4>::bitset(std::bitset<4>&&)'

../Playground/++/10.1.0/bitset:751:11: note: conversion of argument 1 would be ill-formed:

It's 0b (Zero b), not ob or Ob

Thanks!!!

Why did you teach bitwise rotation in a Quiz question 2 and not in this lesson normally?

Why does XOR evaluate to true if all are true when odd? Isn’t it an exclusive or that only and only one should be true? Why and how does odd change it?

The xors are evaluated one after the other

1 XOR

1 XOR

1

the first 2 lines evaluate to 0, we're left with

0 XOR

1

That's 1

I don’t understand your answer. One after the other? XOR evaluates if all 3 bits are exclusive true and are not, it’s all 3 true.

xor has 2 operands. If there are more than 2 operands and you xor them, they're evaluated one after the other

There’s no 0 and no 4th column only a 3rd 1. Are they 2 separate XOR? How and to what does the 3rd XOR relate to first 2 or the second? If XOR is not one sequence by all 3 and it executes only by 2 operands so it overwrites the XOR from the first 2? And doesn’t it overwrite by the last 2 operands that are both 1 so why isn’t it 0 ? because both last 2 that are the last 2 operands are 1.

Also, Why with AND that all supposed to be 1 why isn’t it 0? Because like you said that at the 3rd operands it’s a 0. (What I don’t know what it means like I asked before)

Ok. I got it. It uses the outcome from the first operands for the 3rd.

My solution to Question 2:

I have no idea if this would work with other bits. Your solution seems better tho

Your `else if` is always true. A bit only has 2 possible values, so if it's not 0 (which you checked for in line 3), it must be 1 and you can use an `else`.

Rather than repeating line 4/9, it's better to store the value of bit 3 in a variable and perform the shift unconditionally. If you do that, your code is equivalent to the solution. Functionally, your code is working already.

Just wanted to share my solution for Question 3 here:

Talking about the solution to question #3, it isn't against the best practice of not using an operator with side effects on the same variable in a given statement?

Or, if we put them inside the parenthesis, are evaluated at the same time?

After thinking for solution and finally find one like this

and then saw how it solved already in example, I felt am stupid xD

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 was having the same issue. Due to your explanation I was able to grasp the concept. The main issue for me was not truly understanding the significance of the logic operator OR. Also I thought the shift on bits would apply right away and information would be lost. This is not the case, the OR operator compares both shifts and keeps the result. Working it out in bits made me understand it:

This looks like this (bits2 as example):

1001 (before any shift)

----

0010 (left shift 1 on instance of bits 1001)

0001 (right shift 3 on instance of bits 1001)

---- (we use OR '|' sign to compare the shifts)*

0011 (evaluates to the right answer when we want to rotate left)

If my logic is flawed, someone please correct me.

Thank you Cerezas for the detailed explanation!

Your example is correct.

You are very welcome, keep it up!

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.