简体   繁体   中英

Java >>>= operator

I was wondering, what can the >>>= operator be applied to?

It works for the following:
int >>>= int
long >>>= long
long >>>= int
long >>>= short
short >>>= long
short >>>= short
int >>>= byte

But not for anything including float or double .

Why is that, and how can I make it work for float and double ?

Thank you!

It doesn't make much sense to shift bits around in a float or double considering what the bits represent.

Bit 63 (the bit that is selected by the mask 0x8000000000000000L) represents the sign of the floating-point number. Bits 62-52 (the bits that are selected by the mask 0x7ff0000000000000L) represent the exponent. Bits 51-0 (the bits that are selected by the mask 0x000fffffffffffffL) represent the significand (sometimes called the mantissa) of the floating-point number.

Should you do an shift right on a double, the signbit would be interpreted as exponent, and part of the exponent would spill over to the significand. The semantics of the shift operation would be meaningless.

If you really want to shift the bits around, you can however go via Double.doubleToLongBits and Double.longBitsToDouble as follows:

// Unsigned shift right 3 of a double
Double.longBitsToDouble(Double.doubleToLongBits(d) >>> 3)

From the Java Language Specification

It is a compile-time error if the type of each of the operands of a shift operator, after unary numeric promotion, is not a primitive integral type.

You cannot apply any of the shift operators to floating point type primitive values.

Floating-point types are inherently signed, so >>>= would make little sense for float or double . If you can't use / by a power of 2, then you have a big problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM