在我的应用程序中,我试图显示双变量的位表示。
它适用于较小的双变量。不适用于 10^30 级别。
Code:
#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;
}
Output:
/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构造函数 http://en.cppreference.com/w/cpp/utility/bitset/bitset你会看到它要么接受一个字符串作为参数,要么接受一个integer.
这意味着你的double
value 将被转换为整数,并且没有标准整数类型可以容纳如此大的值,这导致未定义的行为.
如果你想获得实际的位double
你需要做一些铸造技巧才能使其发挥作用:
unsigned long long bits = *reinterpret_cast<unsigned long long*>(&doubleValue);
注意类型双关语 https://en.wikipedia.org/wiki/Type_punningC++规范中没有这样定义,但是只要sizeof(double) == sizeof(unsigned long long)
它会起作用的。如果您希望行为得到明确定义,您必须遍历数组char
and char*
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)