c++ - 如何在 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++ 中没有半精度(16 位)浮点的内置类型。你必须自己计算价值。
推荐阅读
- discord - 在没有公共渠道的情况下写入 Discord 机器人
- webpack - Yarn 努力构建 CSS
- visual-studio - 我为跨平台移动应用程序开发启动了一个新的 Xamarin Forms 项目,并且正在解决问题
- javascript - 除非由 window.location.href 重定向,否则将 URl 设为私有
- build - AOSP R/Q 构建因 clang++ 而失败:错误:clang 前端命令因信号而失败
- opencv - 如果我需要访问底层数据,我应该为 Opencv 图像使用什么格式?
- html - 如何避免 VsCode Prettier 为 html 文件中的每个类换行?
- pre-commit.com - 初始化预提交环境时的工作目录
- python - Django Postgresql 搜索不显示结果
- python - Firestore - 获取所有文档及其子集合