  Course Content

Introduction to C++  Bitwise Shift Operators (Bonus)

This is a byte. A byte consists of 8 bits. Any number can be represented as a sum of twos in different powers (binary).

For example, the number 4 can be represented as 00000100: But how did 0 and 1 become 4?

Blue cells can contain logical 0 or 1. 0 and 1 only indicate the state of the bit.

(0 + 0 + 0 + 0 + 0 + 2² + 0 + 0 = 2 · 2 = 4)

Another example:

The number 5 can be represented as 00000101: 0 + 0 + 0 + 0 + 0 + 2² + 0 + 2⁰ = 4 + 1 = 5 (х⁰ = 1)

Bitwise shift operators move the entire sequence of bits to the right or left, allowing multiplication (`<<`) or division (`>>`) by a power of two.

## Shift left

Shift the number one bit to the left:  After the shift operation, the value of the variable became equal to 8 because 00001000 it's the same as 0 + 0 + 0 + 0 + 2³ + 0 + 0 + 0 = 2 · 2 · 2 = 8.

Next example: Shift the number one bit to the left: After the shift operation, all logical `1` are shifted to the left (2³ + 2¹ = 8 + 2 = 10), and it turns out that number 10 was obtained from the number 5 after the shift, without using the multiplication operation (`*`).

## Shift right

Shift the number one bit to the right:  `1`, which was under `2⁰` "came out", so after the shift operation to the right, the number 5 will become the number 2.

So, shifting one bit to the right multiplies the variable by 2, shifting one bit to the left divides the variable by 2.  main.cpp  Section 3.

Chapter 5