<< - left shift

suggest change
// :glot
#include <iostream>

int main() {
    const int a = 1;      // 0001b
    const int b = a << 1; // 0010b
    
    std::cout << "a = " << a << ", b = " << b << '\n';
}
a = 1, b = 2

Why

The left bit wise shift will shift the bits of the left hand value (a) the number specified on the right (1), essentially padding the least significant bits with 0’s, so shifting the value of 5 (binary 0000 0101) to the left 4 times (e.g. 5 << 4) will yield the value of 80 (binary 0101 0000). You might note that shifting a value to the left 1 time is also the same as multiplying the value by 2, example:

int a = 7;
while (a < 200) {
    std::cout << "a = " << a << '\n';
    a <<= 1;
}

a = 7;
while (a < 200) {
    std::cout << "a = " << a << '\n';
    a *= 2;
}

But it should be noted that the left shift operation will shift all bits to the left, including the sign bit, example:

// :glot
#include <iostream>

int main() {
    const int a = 2147483647; // 0111 1111 1111 1111 1111 1111 1111 1111
    const int b = a << 1;     // 1111 1111 1111 1111 1111 1111 1111 1110
    
    std::cout << "a = " << a << ", b = " << b << '\n';
}
a = 2147483647, b = -2

That output is the C++20 result when int is 32 bits wide. A wider int stays positive. Since C++20, a left shift is the unique value congruent to the mathematical product modulo 2 to the power of the result width. Before C++20, a signed shift whose mathematical result is not representable is undefined. Unsigned types remain the clearest choice for bit manipulation. In every standard, a negative shift count, or a count greater than or equal to the width of the promoted left operand, is undefined:

int a = 1;
int b = a << -1;                  // undefined: negative count
int c = a << (sizeof(int) * 8);   // undefined when a byte has 8 bits: count equals the width

The bit wise left shift does not change the value of the original values unless specifically assigned to using the bit wise assignment compound operator <<=:

// :glot
#include <iostream>

int main() {
    int a = 5;  // 0101b
    a <<= 1;    // a = a << 1;

    std::cout << "a = " << a << '\n';
}
a = 10

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents