左移操作

huangapple go评论92阅读模式
英文:

Left shift operation

问题

  1. 当我执行 j <<= 1,而 j 最初为零时,它最终变成零,而不是正常情况下应该是1。其他初始值通常会加倍。

    有人知道为什么会发生这种情况吗?

  2. 为什么对切片字段进行位运算会导致运行时错误?

英文:
  1. When I execute j <<= 1 while j is initially zero, it ends up as a zero instead of 1 as it normally should be. Any other initial value is normally doubled.

    Does anyone know why this is happening?

  2. Why bitwise operations on slice fields cause runtime errors?

答案1

得分: 7

考虑 j = 0

0000 0000 0000 0000

现在 j <<= 1 是什么?它是:

0000 0000 0000 0000
←                 ↑
移位后         添加

结果是.. 相同的数字(0)。

将一个数字左移1位,相当于将其乘以2,0*2等于0。

英文:

Consider j = 0:

0000 0000 0000 0000

Now what is j <<= 1? It's:

0000 0000 0000 0000
←                 ↑
Shifted         Added

Which is.. the same number (0).

Left shifting a number by 1, is multiplying it by 2, 0*2 is 0.

答案2

得分: 2

如果 j 是零,那么它的所有位都是 0。当你将位向左移动一位时,它们仍然保持为零,并在右侧添加一个新的零位。因此,结果中的所有位都是零,结果就是零。

英文:

If j is zero, all of its bits are 0. When you shift the bits one position to the left, they all remain as zero, and a new zero bit is added on the right. Therefore all the bits in the result are zero, and the result is zero.

huangapple
  • 本文由 发表于 2013年12月31日 21:27:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/20858134.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定