c++ - 在 C++ 中将 double 转换为 (IEEE 754) 64 位二进制字符串表示形式

标签 c++ c string double ieee-754

我有一个双数,我想用 IEEE 754 64 位二进制字符串表示它。 目前我正在使用这样的代码:

double noToConvert;
unsigned long* valueRef = reinterpret_cast<unsigned long*>(&noToConvert);

bitset<64> lessSignificative(*valueRef);
bitset<64> mostSignificative(*(++valueRef));

mostSignificative <<= 32;
mostSignificative |= lessSignificative;

RowVectorXd binArray = RowVectorXd::Zero(mostSignificative.size());
for(unsigned int i = 0; i <mostSignificative.size();i++)
{
    (mostSignificative[i] == 0) ? (binArray(i) = 0) : (binArray(i) = 1);
} 

上面的代码工作正常,没有任何问题。但是如果你看到,我正在使用 reinterpret_cast 并使用 unsigned long。所以,这段代码非常依赖于编译器。谁能告诉我如何编写独立于平台且不使用任何库的代码。我没问题,如果我们使用标准库甚至 bitset,但我不想使用任何机器或编译器相关代码。

提前致谢。

最佳答案

如果您愿意假设 double 是 IEEE-754 double 类型:

#include <cstdint>
#include <cstring>

uint64_t getRepresentation(const double number) {
    uint64_t representation;
    memcpy(&representation, &number, sizeof representation);
}

如果您甚至不想做出这样的假设:

#include <cstring>

char *getRepresentation(const double number) {
    char *representation = new char[sizeof number];
    memcpy(representation, &number, sizeof number);
    return representation;
}

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

相关文章:

c - 如何从二进制文件读取到字符串/数组和 c 中的 int?

c++ - 使用 HWLOC 的 NUMA 系统的 realloc()

c++ - 在 C++ 中返回一个字符串

c - FreeBSD 数据结构与通信

java - 如何在java中将(Java源代码)字符串转换为(HTML实体(十六进制))字符串?

java 字符串a中的字母包含在字符串b中

c++ - 单进单出规则

c++ - 如何指示容器模板参数的类型?

C - 如何完全释放结构数组单元格

c++ - 混合 C/C++ 源的 Makefile