>> 之间的区别和>>运营商

发布于 2024-08-16 09:38:10 字数 193 浏览 2 评论 0原文

如果移位数为正>>>>和>>工作相同。

如果移位数为负>>>>用 1 填充最高有效位,而 >>操作将 MSB 填充为 0。

我的理解正确吗?

如果负数存储时 MSB 设置为 1,而不是 Java 使用的 2 补码方式,那么运算符的行为会完全不同,对吗?

If the shifted number is positive >>> and >> work the same.

If the shifted number is negative >>> fills the most significant bits with 1s whereas >> operation shifts filling the MSBs with 0.

Is my understanding correct?

If the negative numbers are stored with the MSB set to 1 and not the 2s complement way that Java uses the the operators would behave entirely differently, correct?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

怪异←思 2024-08-23 09:38:10

负数的表示方式称为 2 的补码。为了演示其工作原理,以 -12 为例。 12,用二进制表示,是 00001100(假设整数是 8 位,但实际上它们要大得多)。通过简单地反转每一位来获取 2 的补码,即可得到 11110011。然后,只需加 1 即可得到 11110100。请注意,如果再次应用相同的步骤,则会得到正 12。

>>>>>无论如何都会移至零,所以 12 >>>>> 1 应该给你 00000110,即 6,并且 (-12) >>> 1 应该给你 01111010,也就是 122。如果你真的在 Java 中尝试这个,你会得到一个更大的数字,因为 Java 整数实际上比 8 位大得多。

>>移入与最高位相同的位,以便正数保持正数,负数保持负数。 12>> 1是00000110(仍然是6)并且(-12)>> 1 就是 11111010,它是负 6。

The way negative numbers are represented is called 2's complement. To demonstrate how this works, take -12 as an example. 12, in binary, is 00001100 (assume integers are 8 bits though in reality they are much bigger). Take the 2's complement by simply inverting every bit, and you get 11110011. Then, simply add 1 to get 11110100. Notice that if you apply the same steps again, you get positive 12 back.

The >>> shifts in zero no matter what, so 12 >>> 1 should give you 00000110, which is 6, and (-12) >>> 1 should give you 01111010, which is 122. If you actually try this in Java, you'll get a much bigger number since Java ints are actually much bigger than 8 bits.

The >> shifts in a bit identical to the highest bit, so that positive numbers stay positive and negative numbers stay negative. 12 >> 1 is 00000110 (still 6) and (-12) >> 1 would be 11111010 which is negative 6.

眉黛浅 2024-08-23 09:38:10

>> 的定义Java 语言规范中的 运算符

n>>>s的值是n个右移的s位位置,且具有零扩展。如果n为正,则结果与n>>s相同;如果 n 为负数,且左侧操作数的类型为 ,则结果等于表达式 (n>>s)+(2<<~s) 的结果int,如果左侧操作数的类型为 long,则返回表达式 (n>>s)+(2L<<~s) 的结果

Definition of the >>> operator in the Java Language Specification:

The value of n>>>s is n right-shifted s bit positions with zero-extension. If n is positive, then the result is the same as that of n>>s; if n is negative, the result is equal to that of the expression (n>>s)+(2<<~s) if the type of the left-hand operand is int, and to the result of the expression (n>>s)+(2L<<~s) if the type of the left-hand operand is long.

南冥有猫 2024-08-23 09:38:10

恰恰相反,>>用零填充,而>>如果 ho 位为 1,则填充 1。

Just the opposite, the >>> fills with zeros while >> fills with ones if the h.o bit is 1.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文