The difference between >> and >>> in Java

Reprinted from https://www.cnblogs.com/565261641-fzh/p/7686757.html

>>: Signed right shift. A positive number is shifted to the right and the high-order position is filled with 0, and a negative number is shifted to the right and the high-order position is filled with 1. for example:

4 >> 1, the result is 2; -4 >> 1, the result is -2. -2 >> 1, the result is -1.

>>>: Unsigned right shift. Whether it is a positive or negative number, the high bits are filled with 0.

For positive numbers, >> and >>> are no different.

For negative numbers, -2 >>> 1, the result is 2147483647 (Integer.MAX_VALUE), and -1 >>> 1, the result is 2147483647 (Integer.MAX_VALUE).

So, when you want to determine whether two numbers have the same sign, you can do this:

return ((a >> 31) ^ (b >> 31)) == 0;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324690902&siteId=291194637