Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are exponents required for hex real numbers in Java

In Java for example this is a hex number 0x10.

0x10.2P2 is a correct hexadecimal double.

But why is 0x1f.2 not correct? Why can't we use that, while 0x1f.2P1 should give the same result but it works?

like image 395
AMD Avatar asked May 21 '16 16:05

AMD


2 Answers

Well, if you really mean why, we'll have to hope one of those responsible for the syntax will chime in. It looks to me as though making the exponent optional wouldn't hurt the ability to parse the literal, but I haven't considered it in detail. All I can offer is that the Java Language Specification §3.10.2 requires it:

For hexadecimal floating-point literals, at least one digit is required (in either the whole number or the fraction part), and the exponent is mandatory, and the float type suffix is optional. The exponent is indicated by the ASCII letter p or P followed by an optionally signed integer.

like image 163
Erick G. Hagstrom Avatar answered Sep 21 '22 15:09

Erick G. Hagstrom


There's some measure of "why" in this previous Stack Overflow question:

0xp0 prints 0.0 (Hexadecimal Floating Point Literal)

and here:

P in constant declaration

This "best answer" from @NPE gives a justification:

At first glance it might seem that the 0x prefix is sufficient to identify a hex floating-point literal, so why have the Java designers chosen to change the letter from e to p? This has to do with e being a valid hex digit, so keeping it would give rise to parsing ambiguity. Consider:

0x1e+2

Is that a hex double or the sum of two integers, 0x1e and 2? When we change e to p, the ambiguity is resolved:

0x1p+2

like image 31
vielmetti Avatar answered Sep 21 '22 15:09

vielmetti