How can I zero out the last 32 bits of a double, in java, as efficiently as possible?
Asked
Active
Viewed 325 times
-2
-
3Why would you want to zero out the last 32 bits of a double? – JAB May 16 '14 at 17:48
-
6`(x>>32)<<32` ? – But I'm Not A Wrapper Class May 16 '14 at 17:50
-
1You wouldn't want to this on a double since a double is encoded as a coefficient and an exponent. Doing a bitwise operation on a double isn't likely to give you the result you expect. Scaling to a float or converting the number to fixed point might work, depending on the value range. – Baldy May 16 '14 at 17:56
-
You can always do `a = Double.longBitsToDouble(Double.doubleToLongBits(a) & 0xFFFFFFFF00000000L);` – Alexis C. May 16 '14 at 17:58
-
Ignore my last comment...this question should help you convert doubles to bits. That way you can use some bit wise operators, then convert back to a double. http://stackoverflow.com/questions/4211095/xoring-two-doubles-in-java – But I'm Not A Wrapper Class May 16 '14 at 18:00
2 Answers
7
Try this.
private static final long ZERO_OUT_LAST_32_BITS = 0xffffffff00000000L;
public static void main(String[] args) {
double number = 2.5;
long numberBits = Double.doubleToLongBits(number);
double result = Double.longBitsToDouble(numberBits & ZERO_OUT_LAST_32_BITS);
}
It zeroes out the last 32 bits of the binary representation of your double by using a binary AND operation.
However, make sure you know exactly what and why you are doing - I would at least expect an explaining comment next to code like this.
Petr Janeček
- 36,584
- 10
- 122
- 143
5
Convert to long and mask away the desired bits, convert back:
long l = Double.doubleToLongBits();
l &= 0xFFFFFFFF00000000L;
double truncated = Double.longBitsToDouble(l);
Although I'm not sure what you're trying to achive by that...
Durandal
- 19,701
- 3
- 33
- 65