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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Iluvatar
  • 1,537
  • 12
  • 13
  • 13
    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 Dec 06 '16 at 12:08
  • 2
    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 Dec 06 '16 at 12:18
  • Yes, that is correct. (It's also converting it to an int, but that doesn't change anything in this case) – Iluvatar Dec 06 '16 at 12:20
  • 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 Dec 06 '16 at 13:28
  • 8
    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 Dec 06 '16 at 13:29
  • Whoops, somehow i missed that – Puzomor Croatia Dec 06 '16 at 13:31