gpt4 book ai didi

c++ - 将 double 的 64 位二进制字符串表示形式转换回 C++ 中的 double

转载 作者:可可西里 更新时间:2023-11-01 18:26:47 31 4
gpt4 key购买 nike

我有 double 的 IEEE754 double 64 位二进制字符串表示形式。示例: double 值 = 0.999;它的二进制表示是“0011111111101111111101111100111011011001000101101000011100101011”

我想在 C++ 中将此字符串转换回 double 。我不想使用任何外部库或 .dll,因为我的程序可以在任何平台上运行。

最佳答案

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 header 。

关于c++ - 将 double 的 64 位二进制字符串表示形式转换回 C++ 中的 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8616573/

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