简体   繁体   English

C中的十六进制浮点常数

[英]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. 我有一个十六进制浮点常量,我想在我的C程序中直接声明,并避免转换。 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 : 您可以使用0的指数:

float val = 0xDE.488641p0;

Which in more normal looking notation means DE.488641×2 0 (in base 16, of course). 其中更常见的符号表示DE.488641×2 0 (当然是16号)。 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 . 其中常规数学符号表示0.DE488631×2 8 ,或等效于指数的十六进制数,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. 我认为使用0的指数更容易理解,除非你有理由使用第二个例子中的表格。

The C99 Standard specifies that a hexadecimal floating point constant must have an exponent: C99标准规定十六进制浮点常量必须具有指数:

§6.4.4.2 Floating constants §6.4.4.2浮动常数

  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). 根据此定义,您可以看到只有浮动后缀是可选的(即可以附加到浮动常量以强制特定浮动类型的fl )。 As Carl Norum has already suggested, use an exponent of 0 as a “no-op”. 正如Carl Norum已经建议的那样,使用0的指数作为“无操作”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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