gpt4 book ai didi

c++ - 简单的十六进制/ float 转换

转载 作者:太空狗 更新时间:2023-10-29 23:38:06 25 4
gpt4 key购买 nike

我正在 c++ 和 python 程序之间做一些输入/输出(只有浮点值)python 有一个很好的功能,可以将浮点值转换为十六进制数并返回,如您在此链接中所见:

http://docs.python.org/library/stdtypes.html#additional-methods-on-float

在 C++ 中是否有一种简单的方法来实现类似的东西?并将 python 输出转换回 C++ double/float?这样我就不会在两个进程之间交换数据时出现舍入错误的问题......

感谢您的回答!

最佳答案

从您在问题中提供的链接 ( Additional Methods on Float ):

This syntax is similar to the syntax specified in section 6.4.4.2 of the C99 standard, and also to the syntax used in Java 1.5 onwards. In particular, the output of float.hex() is usable as a hexadecimal floating-point literal in C or Java code, and hexadecimal strings produced by C’s %a format character or Java’s Double.toHexString are accepted by float.fromhex().

例子:

#include <cstdio>

int main() {
float f = 42.79;
printf("%.2f == %a\n", f, f);
fscanf(stdin, "%a", &f);
printf("%.2f == %a\n", f, f);
}

运行它:

$ g++ *.cpp && (python -c'print 12.34.hex()' | ./a.out )

输出:

42.79 == 0x1.5651ecp+5
12.34 == 0x1.8ae148p+3

关于c++ - 简单的十六进制/ float 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2427034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com