问题
If the shifted number is positive >>> and >> work the same.
If the shifted number is negative >>> fills the most significant bits with 1s whereas >> operation shifts filling the MSBs with 0.
Is my understanding correct?
If the negative numbers are stored with the MSB set to 1 and not the 2s complement way that Java uses the the operators would behave entirely differently, correct?
回答1:
The way negative numbers are represented is called 2's complement. To demonstrate how this works, take -12 as an example. 12, in binary, is 00001100 (assume integers are 8 bits though in reality they are much bigger). Take the 2's complement by simply inverting every bit, and you get 11110011. Then, simply add 1 to get 11110100. Notice that if you apply the same steps again, you get positive 12 back.
The >>> shifts in zero no matter what, so 12 >>> 1 should give you 00000110, which is 6, and (-12) >>> 1 should give you 01111010, which is 122. If you actually try this in Java, you'll get a much bigger number since Java ints are actually much bigger than 8 bits.
The >> shifts in a bit identical to the highest bit, so that positive numbers stay positive and negative numbers stay negative. 12 >> 1 is 00000110 (still 6) and (-12) >> 1 would be 11111010 which is negative 6.
回答2:
Definition of the >>> operator in the Java Language Specification:
The value of
n>>>sis n right-shifted s bit positions with zero-extension. If n is positive, then the result is the same as that ofn>>s; if n is negative, the result is equal to that of the expression(n>>s)+(2<<~s)if the type of the left-hand operand isint, and to the result of the expression(n>>s)+(2L<<~s) if the type of the left-hand operand islong.
回答3:
Just the opposite, the >>> fills with zeros while >> fills with ones if the h.o bit is 1.
来源:https://stackoverflow.com/questions/1972356/difference-between-and-operators