在C++中转储六角浮点
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: %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 年标准以来一直存在。
相关文章:
- 如何在openssl-ecc中获取十六进制格式的私钥
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 为什么mpfr_printf与十六进制浮点(%a转换说明符)的printf不同
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 指向存储在字符串 c++ 中的十六进制
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C ++如何使用UTF8十六进制代码打印UTF8符号?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 如何在C++中将十六进制字符串转换为文本数据
- 使用 sprintf 将十六进制0xAABBCC转换为字符串"AA:BB:CC"
- 绝对编码器十六进制输入
- 为什么C++总是显示十六进制内存地址,而不仅仅是整数?
- C++17 十六进制浮点文字单精度后缀冲突?
- 六角字符串到UTF-8(UNICODE)字符串
- 十六进制的六角字节
- 在C++中转储六角浮点