Why is 1 << 3 equal to 8 and not 6?
This question already has an answer here:
Shifting a number to the left is equivalent to multiplying that number by 2n where n
is the distance you shifted that number.
To see how is that true lets take an example, suppose we have the number 5
so we shift it 2
places to the left, 5
in binary is 00000101
ie
0×27 + 0×26 + 0×25 + 0×24 + 0×23 + 1×22 + 0×21 + 1×20 = 1×22 + 1×20 = 4 + 1 = 5
now, 5 << 2
would be 00010100
ie
0×27 + 0×26 + 0×25 + 1×24 + 0×23 + 1×22 + 0×21 + 0×20 = 1×24 + 1×22 = 16 + 4 = 20
But we can write 1×24 + 1×22 as
1×24 + 1×22 = (1×22 + 1×20)×22 = 5×4 → 20
and from this, it is possible to conclude that 5 << 2
is equivalent to 5×22, it would be possible to demonstrate that in general
k << m = k×2m
So in your case 1 << 3
is equivalent to 23 = 8, since
1 << 3
→ b00000001 << 3
→ b00001000
→ 23 -> 8
If you instead did this 3 << 1
then
3 << 1
→ b00000011 << 1
→ b00000110
→ 22 + 21 → 4 + 2 → 6
1 in binary is 0000 0001
by shifting to left by 3 bits (ie 1 << 3
) you get
0000 1000
Which is 8 in decimal and not 6.
因为两个三的力量是八。
链接地址: http://www.djcxy.com/p/12570.html上一篇: 什么是1 << 1的值? 如何计算它?
下一篇: 为什么1 << 3等于8而不是6?