JavaScript code:
alert( -123456 >>> 0 ); // Prints 4294843840
Java code:
System.out.println( -123456 >>> 0 ); // Prints -123456
Why? I've read documentation, but I didn't find the difference. How do I port JavaScript code to Java?
为什么?我已阅读文档,但我没有发现差异。如何将JavaScript代码移植到Java?
1 个解决方案
#1
34
Both are the logical right shift, but JavaScript has some weirdness in how it handles numbers. Normally numbers in JavaScript are floats, but the bitwise operations convert them to unsigned 32 bit integers. So even though the value looks like it shouldn't change, it converts the number to a 32 bit unsigned integer.
两者都是合乎逻辑的右移,但JavaScript在如何处理数字方面有一些奇怪之处。通常,JavaScript中的数字是浮点数,但按位运算将它们转换为无符号的32位整数。因此,即使该值看起来不应该更改,它也会将数字转换为32位无符号整数。
The value that you see 4294843840
is just the same bits as -123456
, but interpreted as unsigned instead of signed.
您看到的值4294843840与-123456的位相同,但解释为unsigned而不是signed。
#1
34
Both are the logical right shift, but JavaScript has some weirdness in how it handles numbers. Normally numbers in JavaScript are floats, but the bitwise operations convert them to unsigned 32 bit integers. So even though the value looks like it shouldn't change, it converts the number to a 32 bit unsigned integer.
两者都是合乎逻辑的右移,但JavaScript在如何处理数字方面有一些奇怪之处。通常,JavaScript中的数字是浮点数,但按位运算将它们转换为无符号的32位整数。因此,即使该值看起来不应该更改,它也会将数字转换为32位无符号整数。
The value that you see 4294843840
is just the same bits as -123456
, but interpreted as unsigned instead of signed.
您看到的值4294843840与-123456的位相同,但解释为unsigned而不是signed。