在我的应用程序中,我试图显示 double 变量的位表示。 它适用于较小的双变量。不适用于 10^30 级别。
代码:
#include <iostream>
#include <bitset>
#include <limits>
#include <string.h>
using namespace std;
void Display(double doubleValue)
{
bitset<sizeof(double) * 8> b(doubleValue);
cout << "Value : " << doubleValue << endl;
cout << "BitSet : " << b.to_string() << endl;
}
int main()
{
Display(1000000000.0);
Display(2000000000.0);
Display(3000000000.0);
Display(1000000000000000000000000000000.0);
Display(2000000000000000000000000000000.0);
Display(3000000000000000000000000000000.0);
return 0;
}
输出:
/home/sujith% ./a.out
Value : 1e+09
BitSet : 0000000000000000000000000000000000111011100110101100101000000000
Value : 2e+09
BitSet : 0000000000000000000000000000000001110111001101011001010000000000
Value : 3e+09
BitSet : 0000000000000000000000000000000010110010110100000101111000000000
Value : 1e+30
BitSet : 0000000000000000000000000000000000000000000000000000000000000000
Value : 2e+30
BitSet : 0000000000000000000000000000000000000000000000000000000000000000
Value : 3e+30
BitSet : 0000000000000000000000000000000000000000000000000000000000000000
我担心的是为什么 bitset 总是给出 64,后面的 3 为零。有趣的是,实际值的“cout”按预期工作。
最佳答案
如果你看the std::bitset
constructor您会看到它要么接受一个字符串作为参数,要么接受一个整数。
这意味着您的 double
值将被转换为整数,并且没有标准的整数类型可以容纳如此大的值,这会导致未定义的行为。
如果你想得到 double
的实际位,你需要做一些转换技巧来让它工作:
unsigned long long bits = *reinterpret_cast<unsigned long long*>(&doubleValue);
请注意 type-punning像这样在 C++ 规范中没有定义,但只要 sizeof(double) == sizeof(unsigned long long)
它就可以工作。如果您希望行为定义明确,则必须遍历 char
和 char*
数组。
关于c++ - 使用 std::bitset 进行双重表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40737116/