Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

hex - Java hexadecimal base double literal

I am studying for java certification. And i'm curious about the java literals. I know it is possible to do something like this:

int i = 0xAA;
long l = 0xAAL;

Also this is possible for floating-point variables:

double d = 123d;
float f = 123f;

So I logically thought with these examples that the same would apply for hexadecimal. Just like i can add L for long literals, I could add 'd' or 'f' but the logic is flawed since 'F' and 'D' are valid hexadecimal values.

It is not possible to do something like this:

double d = 0xAAAAAAAAAAAAAAAAAAd;

Is this just not allowed by Java or there is a simple way to do it that I don't know?

question from:https://stackoverflow.com/questions/42722895/java-hexadecimal-base-double-literal

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...