简体   繁体   中英

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.

You can use an exponent of 0 :

float val = 0xDE.488641p0;

Which in more normal looking notation means DE.488641×2 0 (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×2 8 , or equivalently with a hexadecimal base for the exponent, 0.DE488631×16 2 .

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.

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 (ie 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”.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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