Search

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:

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

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:

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:

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:

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

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

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

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

The following code should execute:

and print the following:

0010
0011

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
Index
O.1 -- Bit flags and bit manipulation via std::bitset

178 comments to O.2 — Bitwise operators

  • Simp0L

    Is this solution for the question#2 correct?

  • Simp0L

    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"?

  • kutlu

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

  • scranton

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

  • Martin

    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.

    • nascardriver

      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.

  • Chayim

    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)

  • Chayim

    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:

  • Chayim

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

  • Chayim

    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?

    • nascardriver

      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

      • Chayim

        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.

        • nascardriver

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

  • Tony

    My solution to Question 2:

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

    • nascardriver

      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.

  • Daffy

    Just wanted to share my solution for Question 3 here:

  • goiu

    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?

  • Amir

    After thinking for solution and finally find one like this

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

  • Matt

    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!

  • Obito

    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

    • nascardriver

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

  • mohamed

    what the 'u' character here stand for ?
    std::bitset<4>{ ~0b0100u }

  • Simon

    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:

  • bobby

    oh man, there was this brilliant method in comparison to my
    num x 10
    if num > 10000, num - 10000 + 1

  • internet_laser

    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.

    • Cerezas

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

      • internet_laser

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

  • internet_laser

    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.

  • internet_laser

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

  • Denis

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

  • Raffaello

    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?

    • nascardriver

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

  • MoisturBacon

    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.

  • Mike

    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.

    • nascardriver

      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!

Leave a Comment

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