Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between operator >>> in Java and JavaScript?

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?

like image 249
Kirillius Labutin Avatar asked Dec 06 '16 11:12

Kirillius Labutin


People also ask

What is the difference between >> and >>> operators in JavaScript?

>> is arithmetic shift right, >>> is logical shift right. In an arithmetic shift, the sign bit is extended to preserve the signedness of the number.

Is there a difference between Java and JavaScript?

Java creates applications that run in a virtual machine or browser while JavaScript code is run on a browser only. Java code needs to be compiled while JavaScript code are all in text. They require different plug-ins.

Does Java and JavaScript have the same syntax?

JavaScript(JS) is not similar or related to Java. Both the languages have a C-like syntax and are widely used in client-side and server-side Web applications, but there are few similarities only. Features of Javascript are as follows: JavaScript was created in the first place for DOM manipulation.

Which is better between Java and JavaScript?

While Java is extensive, faster, and supports better app development process, JavaScript is lighter and better suited for interactive apps. So, Java or JavaScript, pick the language as per your development need.


1 Answers

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.

like image 180
Iluvatar Avatar answered Sep 20 '22 05:09

Iluvatar