简体   繁体   English

如何将十进制数转换为64位二进制浮点数?

[英]How to convert decimal number into 64 bit binary float number?

I need to convert decimal number into 64 bit binary float value. 我需要将十进制数转换为64位二进制浮点值。 If you know any algorithm or anything about it then please help. 如果您知道任何算法或其相关知识,请提供帮助。

使用boost :: lexical_cast

double num = lexical_cast<double>(decimal);

Assuming you mean a decimal stored inside a string, atof would be a standard solution to convert that to a double value (which is a 64-bit floating point number on the x86 architecture). 假设您的意思是将一个小数存储在字符串中,那么atof是将其转换为double值(x86体系结构上为64位浮点数)的标准解决方案。

std::string s = "0.4";
double convertedValue = atof(s.c_str());

Or similar for C strings: 或类似的C字符串:

const char *s = "0.4";
double convertedValue = atof(s);

But if you mean integer number by "decimal number", then just write 但是,如果您用“小数”表示整数,则只需写

int yourNumber = 100;
double convertedValue = yourNumber;

and the value will automatically be converted. 值将自动转换。

Value casting from a string to double can be implemented by boost::lexical_cast. 从字符串到双精度值的强制转换可以通过boost :: lexical_cast实现。 Type casting from int to double is a part of C++: 从int到double的类型转换是C ++的一部分:

double d = (double)i;

It was already mentioned in the previous replies. 在先前的答复中已经提到过。

If you are interested to know how this casting is implemented, you may refer the sources of the C standard library your compiler is using given that the sources are provided and no floating point co-processor is used for this purpose. 如果您想知道这种转换是如何实现的,可以参考编译器使用的C标准库的源代码,前提是提供了源代码,并且没有为此目的使用浮点协处理器。 Many embedded target compilers do this work "manually" if no floating point co-processor is available. 如果没有浮点协处理器,许多嵌入式目标编译器会“手动”完成这项工作。

For the binary format description, please see Victor's reply 有关二进制格式的说明,请参见Victor的回复

Decimal decimalNumber = 1234;
Float binaryFloatValue = decimalNumber;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM