30

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?

2

1 Answer 1

35

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.

The value that you see 4294843840 is just the same bits as -123456, but interpreted as unsigned instead of signed.

Sign up to request clarification or add additional context in comments.

6 Comments

Minor nit; they're not "float-like", they're explicitly IEEE-754, all the time. The issue here comes from the internal, temporary conversion.
so basically in both java and javascript, in this example, no 'right-shifting' is taking place (since the shift is '0'), but rather, in javascript, it is only converting the number to an unsigned number. is this understanding correct?
Yes, that is correct. (It's also converting it to an int, but that doesn't change anything in this case)
It could be worth noting that this probably isn't a language-specific thing but rather a difference between a specific compiler and a specific interpreter. Java also obviously converts signed to unsigned, but in OP's example it's optimized away - so nothing happens. In answer that @kishan-c-s provided, it's clear that Java also converts to unsigned int, but JS just doesn't optimize away the operation.
Java doesn't have unsigned ints. @kishan-c-s example wasn't a conversion based on the operator, it was the result of the operation itself that caused the value to go positive.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.