我有一个IEEE754双精度64位二进制字符串表示的双精度数字。示例: double值= 0.999;其二进制表示为"0011111111101111111101111100111011011001000101101000011100101011“
我想在c++中将这个字符串转换回双精度数。我不想使用任何外部库或.dll,因为我的程序可以在任何平台上运行。
发布于 2011-12-23 21:31:30
C字符串解决方案:
#include <cstring> // needed for all three solutions because of memcpy
double bitstring_to_double(const char* p)
{
unsigned long long x = 0;
for (; *p; ++p)
{
x = (x << 1) + (*p - '0');
}
double d;
memcpy(&d, &x, 8);
return d;
}std::string解决方案:
#include <string>
double bitstring_to_double(const std::string& s)
{
unsigned long long x = 0;
for (std::string::const_iterator it = s.begin(); it != s.end(); ++it)
{
x = (x << 1) + (*it - '0');
}
double d;
memcpy(&d, &x, 8);
return d;
}通用解决方案:
template<typename InputIterator>
double bitstring_to_double(InputIterator begin, InputIterator end)
{
unsigned long long x = 0;
for (; begin != end; ++begin)
{
x = (x << 1) + (*begin - '0');
}
double d;
memcpy(&d, &x, 8);
return d;
}示例调用:
#include <iostream>
int main()
{
const char * p = "0011111111101111111101111100111011011001000101101000011100101011";
std::cout << bitstring_to_double(p) << '\n';
std::string s(p);
std::cout << bitstring_to_double(s) << '\n';
std::cout << bitstring_to_double(s.begin(), s.end()) << '\n';
std::cout << bitstring_to_double(p + 0, p + 64) << '\n';
}注意:我假设unsigned long long是64位的。一个更干净的解决方案是包含<cstdint>并使用uint64_t,假设您的编译器是最新的并提供C++11头文件。
发布于 2011-12-23 21:23:40
首先要遍历字符串中的各个字符,并设置现有double的各个位。
发布于 2011-12-23 21:27:32
它真的是一个二进制位的字符串吗?如果是这样,首先将其转换为64位int。然后,要么使用库例程(可能在某个地方就有一个),要么更简单地使用64位整数上的别名double来转换为double。
(如果它已经是64位int,那么跳过第一步。)
https://stackoverflow.com/questions/8616573
复制相似问题