在c ++中将双数转换为(IEEE 754)64位二进制字符串表示

jer*_*ome 3 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);
} 
Run Code Online (Sandbox Code Playgroud)

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

提前致谢.

Ste*_*non 5

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

#include <cstdint>
#include <cstring>

uint64_t getRepresentation(const double number) {
    uint64_t representation;
    memcpy(&representation, &number, sizeof representation);
}
Run Code Online (Sandbox Code Playgroud)

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

#include <cstring>

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