首页 > 解决方案 > 如何在 C++ 中将十进制转换为 IEEE 754 半精度格式?

问题描述

我目前正在尝试将十进制值转换为 IEEE 754 半精度浮点格式,但在转换时遇到了一些问题。目前,此代码仅适用于转换为单精度格式。

如果我没记错的话,它默认将十进制值转换为单精度格式。否则,哪一行代码正在这样做?

否则,有没有其他方法可以解决我的问题?

#include <limits.h>
#include <iostream>
#include <math.h>
#include <bitset>

// Get 32-bit IEEE 754 format of the decimal value
std::string GetBinary32( float value )
{
    union
    {
         float input;   // assumes sizeof(float) == sizeof(int)
         int   output;
    }    data;

    data.input = value;

    std::bitset<sizeof(float) * CHAR_BIT>   bits(data.output);

    std::string mystring = bits.to_string<char, 
                                          std::char_traits<char>,
                                          std::allocator<char> >();

    return mystring;
}


int main()
{
    // Convert 19.5 into IEEE 754 binary format..
    std::string str = GetBinary32( (float) 19.5 );
    std::cout << "Binary equivalent of 19.5:" << std::endl;
    std::cout << str << std::endl << std::endl;

    return 0;
}

上述代码的输出将给出01000001100111000000000000000000

但是,我想将其转换为 16 位格式。

编辑:不是重复的,因为这与精度错误无关。

标签: c++floating-pointfloating-point-conversion

解决方案


c++ 中没有半精度(16 位)浮点的内置类型。你必须自己计算价值。


推荐阅读