Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
    
If you want a signed right shift in JS, use >>. – Bergi 8 mins ago
up vote 29 down vote accepted

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.

share|improve this answer
9  
Minor nit; they're not "float-like", they're explicitly IEEE-754, all the time. The issue here comes from the internal, temporary conversion. – Dave Newton 8 hours ago
1  
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? – Zeeshan Arif 8 hours ago
    
Yes, that is correct. (It's also converting it to an int, but that doesn't change anything in this case) – Iluvatar 8 hours ago
    
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. – Puzomor Croatia 7 hours ago
6  
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. – Iluvatar 7 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.