在C ++中转储十六进制浮点数 [英] Dump hex float in C++

查看:225
本文介绍了在C ++中转储十六进制浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过以下:

std::cout << std::hex << 17.0625;

但是它以十进制转储。我想看到11.01(十六进制为17.0625)。如何以十六进制打印一些浮点值?

But it dumped it in decimal. I'd like to see 11.01 (17.0625 in hex). How can I print some floating point value in hex?

请不要提供类似的解决方案:

Please do not offer solutions like:

void outhexdigits(std::ostream& out, fp_t d, int max_chars=160)
{
    while(d > 0. && max_chars)
    {
        while(d < 1. && max_chars){
            out << '0';
            --max_chars;
            d*=16;
        }

        if (d>=1. && max_chars) {
            int i = 0;
            while (d>=1.)
                ++i, --d;
            out << std::hex << i;
            --max_chars;
        }
    }
}

STL / boost中十六进制的浮点数?

Is there any way to dump float numbers in hex in STL/boost?

推荐答案

其他人已经建议了一个C ++ 11解决方案,但是你的问题没有C ++ 11标签。这里是ISO C99解决方案,使用ISO C99标准中的%a 格式说明符。

Others have already suggested a C++11 solution but your question doesn't have the C++11 tag. Here is an ISO C99 solution, using the %a and %la format specifiers from the ISO C99 Standard.


我想看到11.01(十六进制为17.0625)。

I'd like to see 11.01 (17.0625 in hex).

以下程序打印 0X1.11P + 4

#include <stdio.h>

int main() {

  double x = 17.0625;

  printf("17.0625 in hexadecimal is: %A\n", x);  

}






是显示如何以十六进制格式读取和写入浮点数的示例。


Here is an example showing how to read and write floating point numbers in hexadecimal format.

#include <stdio.h>

int main() {

  double x = 0.1;

  char* str = "0X1.999999999999AP-4";

  printf("0.1 in hexadecimal is: %A\n", x);

  printf("Now reading %s\n", str);

  /* in a production code I would check for errors */
  sscanf(str, "%lA", &x); /* note: %lA is used! */

  printf("It equals %g\n", x);

}



如果可移植性很重要,这是我认为合理的方法。

If portability matters or you are stuck with an older compiler, it is a reasonable approach in my opinion.

这篇关于在C ++中转储十六进制浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆