简体   繁体   English

Java十六进制基数双字面

[英]Java hexadecimal base double literal

I am studying for java certification. 我正在攻读java认证。 And i'm curious about the java literals. 而且我对java文字感到好奇。 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. 就像我可以为长文字添加L一样,我可以添加'd'或'f'但逻辑是有缺陷的,因为'F'和'D'是有效的十六进制值。

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? 这是Java不允许的还是有一种我不知道的简单方法吗?

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 . JLS的3.10.2节给出了浮点文字的结构,包括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. p是二进制指数的一部分 - p之后的值是左移值的位数。 Other examples: 其他例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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