0

I am new to c++ and I was playing around. I tried to do int << int, and it gave me unexpected results.

What is the behavior or the math behind the insertion operator, if you use it on two numbers. I didn't find anything in the documentation either.

I hope someone can clear this up.

I also tried some sequences:

Here i assumed its the power of 1, but it is clearly not its the power of 2.

1 << 1 = 2
1 << 2 = 4
1 << 3 = 8
1 << 4 = 16
1 << 5 = 32
1 << 6 = 64
1 << 7 = 128
1 << 8 = 256
1 << 9 = 512
1 << 10 = 1024
1 << 11 = 2048
1 << 12 = 4096
1 << 13 = 8192
1 << 14 = 16384
1 << 15 = 32768
1 << 16 = 65536
1 << 17 = 131072
1 << 18 = 262144
1 << 19 = 524288
1 << 20 = 1048576
1 << 21 = 2097152
1 << 22 = 4194304
1 << 23 = 8388608
1 << 24 = 16777216
1 << 25 = 33554432
1 << 26 = 67108864
1 << 27 = 134217728
1 << 28 = 268435456
1 << 29 = 536870912
1 << 30 = 1073741824 

3 << 0 = 3
3 << 1 = 6
3 << 2 = 12
3 << 3 = 24
3 << 4 = 48
3 << 5 = 96
3 << 6 = 192
3 << 7 = 384
3 << 8 = 768
3 << 9 = 1536
3 << 10 = 3072
3 << 11 = 6144
3 << 12 = 12288
3 << 13 = 24576
3 << 14 = 49152
3 << 15 = 98304
3 << 16 = 196608
3 << 17 = 393216
3 << 18 = 786432
3 << 19 = 1572864
3 << 20 = 3145728
3 << 21 = 6291456
3 << 22 = 12582912
3 << 23 = 25165824
3 << 24 = 50331648
3 << 25 = 100663296
3 << 26 = 201326592
3 << 27 = 402653184
3 << 28 = 805306368
3 << 29 = 1610612736
  • 3
    `<<` in this context is not an insertion operator, since there is no `ostream` involved. It is actually the bitwise left-shift operator instead. Read up on how bits work, and what it means to shift bits left and right. – Remy Lebeau May 08 '20 at 16:20
  • 1
    The operator `<<` is just syntax. It only has meaning when applied to specific types. With streams, it's the insertion operator, with ints, it's a bitwise left shift operator. – cigien May 08 '20 at 16:20

0 Answers0