Java hexadecimal base double literal

It turns out it is possible, although that surprised me. Section 3.10.2 of the JLS gives the structure of floating point literals, including HexadecimalFloatingPointLiteral.

public class Test {

    public static void main(String[] args) {
        double d1 = 0xAAAAAAAAAAAAAAAAAAp0d;
        double d2 = 0x1.8p1d;

        System.out.println(d1); // A very big number
        System.out.println(d2); // 24 = 1.5 * 2^1
    }
}

The p is required as part of the binary exponent – the value after the p is the number of bits to shift the value left. Other examples:

0x1.4p0d => 1.25 (binary 0.01 shifted 0 bits)
0x8p-4d => 0.5 (binary 1000 shifted *right* 4 bits)

Leave a Comment