Hex floats

Index, feed.

[ Date | 2026-08-31 21:25 -0400 ]

After years of barely acknowledging the existence of a syntax for hexadecimal floating point literals, I accidentally printed one, through the use of printf with a percent sign in the wrong location, resulting in %a within my format string.

I understand that hex floats exists to provide an unambiguous and relatively terse way of expressing exact floating point values, where a decimal syntax would need expertise and numerous digits to retain a specific value after going through parsing and printing. Perhaps there are other reasons, but regardless I never felt the need to use that syntax.

My example printed what was supposed to be the current year, 2026, as 0xf.d4p+7. This was pretty confusing, since I expected to see 2026, and also since this ended up in the middle of a string I had meant to output literally.

Hex float syntax

The Linux man page1 for printf(3) says, about conversion specifier a:

For a conversion, the double argument is converted to hexadecimal notation (using the letters abcdef) in the style [-]0xh.hhhhp±d […]. There is one hexadecimal digit before the decimal point, and the number of digits after it is equal to the precision. The default precision suffices for an exact representation of the value if an exact representation in base 2 exists and otherwise is sufficiently large to distinguish values of type double. The digit before the decimal point is unspecified for nonnormalized numbers, and nonzero but otherwise unspecified for normalized numbers.

From this I get that:

Hex float literal input

Hex float literals work consistently for input in the three languages I tested above for output; normalizing for their preferred format:

# Bash
$ printf '%a\n' 0x1.fa8p+10 0xf.d4p+7
0xf.d4p+7
0xf.d4p+7

# Perl
$ perl -E 'printf "%a\n%a\n", 0x1.fa8p+10, 0xf.d4p+7'
0x1.fa8p+10
0x1.fa8p+10

# C
printf("%a\n%a\n", 0x1.fa8p+10, 0xf.d4p+7);
0x1.fa8p+10
0x1.fa8p+10

  1. Dated 2020-11-01.↩︎

  2. C implementation:

    #include <stdio.h>
    
    int main(void) {
        printf("%a\n", 2026.0);
    
        return 0;
    }
    ↩︎

www.kurokatta.org


www.kurokatta.org

Quick links:

Photos
Montréal
Oregon
Paris
Camp info 2007
Camp Faécum 2007
--more--
Doc
Jussieu
Japanese adjectives
Muttrc
Bcc
Montréal
Couleurs LTP
French English words
Petites arnaques
--more--
Hacks
Statmail
DSC-W17 patch
Scarab: dictionnaire de Scrabble
Sigpue
Recipes
Omelette soufflée au sirop d'érable
Camembert fondu au sirop d'érable
La Mona de Tata Zineb
Cake aux bananes, au beurre de cacahuètes et aux pépites de chocolat
*