我有一个双数,我想用 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/