在C++中转储六角浮点

Dump hex float in C++

本文关键字:六角 C++ 转储      更新时间:2023-10-16

我尝试了以下操作:

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

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

请不要提供以下解决方案:

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 中以十六进制转储浮点数?

尝试cout << std::hexfloat << 1.0625;这需要C++11。

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

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

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

#include <stdio.h>
int main() {
  double x = 17.0625;
  printf("17.0625 in hexadecimal is: %An", x);  
}

下面是一个示例,显示如何以十六进制格式读取和写入浮点数。

#include <stdio.h>
int main() {
  double x = 0.1;
  char* str = "0X1.999999999999AP-4";
  printf("0.1 in hexadecimal is: %An", x);
  printf("Now reading %sn", str);
  /* in a production code I would check for errors */
  sscanf(str, "%lA", &x); /* note: %lA is used! */
  printf("It equals %gn", x);
}

如果可移植性很重要,或者您坚持使用较旧的编译器,我认为这是一种合理的方法。

std::hexfloat 是一种格式操纵器,用于以十六进制表示形式打印浮点值。它自 2011 年标准以来一直存在。