Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hexadecimal floating-point constants in C

I've got a hexadecimal floating-point constant which I'd like to declare directly in my C program, and avoid conversion. I believe it must be normalized first, right? How do I normalize it and declare it?

// hex constant 0xDE.488631  
double val = 0xDE.488631; // Error must have exponent.
double val = 0x0.DE488631p-2;  // Pretty sure this is wrong.
like image 566
Malcolm P. Avatar asked Mar 29 '11 23:03

Malcolm P.


2 Answers

You can use an exponent of 0:

float val = 0xDE.488641p0;

Which in more normal looking notation means DE.488641×20 (in base 16, of course). Your guess was close - the exponent is a binary exponent, not a hex exponent, though. You're also using a negative exponent when you want to have a positive exponent. Correcting your second example, you can use:

float val = 0x0.DE488631p8;

Which in regular mathematical notation means 0.DE488631×28, or equivalently with a hexadecimal base for the exponent, 0.DE488631×162.

I think using an exponent of 0 is a lot easier to understand unless you have some reason to use the form from your second example.

like image 154
Carl Norum Avatar answered Sep 17 '22 22:09

Carl Norum


The C99 Standard specifies that a hexadecimal floating point constant must have an exponent:

§6.4.4.2 Floating constants

    hexadecimal-floating-constant:  
        hexadecimal-prefix hexadecimal-fractional-constant  
            binary-exponent-part floating-suffix[opt]  
        hexadecimal-prefix hexadecimal-digit-sequence  
            binary-exponent-part floating-suffix[opt]

From this definition, you can see that only the floating-suffix is optional (i.e. the f or l that can be appended to a floating constant to force a particular floating type). As Carl Norum has already suggested, use an exponent of 0 as a “no-op”.

like image 22
dreamlax Avatar answered Sep 21 '22 22:09

dreamlax