September 15, 2004Hex Floating Point: 0Xf.aP1 == 31.25Ugh! I've been following the new language features of Java 5.0 very, very closely, but this ugly one slipped right by me. We can now write floating point literals using hexadecimal notation. This allows literals to map directly to the bits of a float or a double, I guess. Here are the unpleasant details: A floating-point literal in hexadecimal notation begins with "0X" or "0x". This is followed by the hexadecimal significand. The catch is that this significand may include a decimal point (a hexadecimal point?). After the significand comes the exponent, which is required. Instead of using e or E to introduce the exponent, hexadecimal floating-point literals use p or P. (Think "power" as a mnemonic). The p or P is followed by the exponent, which must be a decimal number, not a hexadecimal number. And this is a binary exponent, not a decimal exponent. That is, is represents the power of two to which the significand should be raised. Finally, the whole thing can be followed by an f or F to indicate a float literal or a d or D to indicate a double literal, just as a decimal floating-point literal can. Here are some examples:
public class Hex {
public static void main(String[] args) {
double x = 0XaP0; // 10 * 2^0 = 10
double y = 0XfP2D; // 15 * 2^2 = 60
float z = 0Xf.aP1F; // (15 + 10/16ths) * 2^1 = 31.25
System.out.printf("%f %f %f%n", x, y, z);
}
}
This change is a Sun-internal one, and was not the result of any JSR through the Java Community Process.
| TrackBack
|