簡體   English   中英

在C ++中轉儲hex float

[英]Dump hex float in C++

我試過以下:

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: %A\n", x);  

}

下面是一個示例,說明如何以十六進制格式讀取和寫入浮點數。

#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);

}

如果可移植性很重要或者您遇到了較舊的編譯器,我認為這是一種合理的方法。

std::hexfloat是一種格式操縱器,用於以十六進制表示形式打印浮點值。 它自2011年標准以來就已存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM