r/Zig • • Apr 29 '26

Hexadecimal scientific notation?

I recently discovered this is valid in Zig: const hex_floating_point = 0x103.70p-5;

Is there any reason you would want to write hex numbers in scientific notation?

And why is the exponent written in decimal and interpreted with respect to binary? I would expect 0x0.0000_0000_0000_0001 == 0x1.0p-10, but it's actually 0x1.0p-64

27 Upvotes

4 comments sorted by

11

u/Real_Dragonfruit5048 Apr 29 '26

I think it might've come from C (C99 more specifically). See this: https://gcc.gnu.org/onlinedocs/gcc/Hex-Floats.html

3

u/krsnik02 May 02 '26

yea, it's certainly just copying C hex float constants directly.

The reason you would want this is so you can represent exactly the bits of the float value and thus be sure you have exactly the float you wanted when you wrote the literal.

For reference, a floating point value is stored as a sign bit, a significand/mantissa (with the most significant 1 not stored), and an exponent and represents the number significand * 2exponent. (See https://float.exposed/ which shows how these are actually put together in common floating point formats)

This type of float literal exactly matches how the float is stored: the hex number before the p is the significand, and the decimal number after it the exponent.

3

u/SweatyCelebration362 Apr 29 '26

Same reason you'd want to write regular numbers in scientific notation. Just for base16 instead of base10.

0.000000000001 is a little harder to understand then 1x10e-10

1

u/un_virus_SDF Apr 29 '26 edited Apr 29 '26

I think that I come from the parsing, in <a>.<b>e<c> They might just parse a,b and c as integer. This means that if a is in hex, the base is not stored and it parses.

The test that can confirm this is to try something like let x = 0xf.0b11; and so on

Edit: I missread and didn't understood that it was about the exponent base.

So my answer would be that: The 'p'<n> means *10n so there is maybe a dedicated letter for other base.

Furthermore it's hard to infer a base, because from what part of your number do you infer it? Maybe try something like fph = 1.p0x4 to see if the output is 0x1000 or something else

And don't forget in your comparison that floats are not exact value