使用std :: bitset进行双重表示 [英] Using std::bitset for double representation

查看:124
本文介绍了使用std :: bitset进行双重表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我试图显示双精度变量的位表示形式。
它适用于较小的double变量。

In my application i'm trying to display the bit representation of double variables. It works for smaller double variables. Not working for 10^30 level.

代码:

#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

我担心的是为什么设置位总是给出64,以后给出3。零。有趣的是,实际值的 cout按预期工作。

My worry is why bitset always gives 64, zero for later 3. Interestingly "cout" for the actual values works as expected.

推荐答案

std :: bitset 构造函数,您将看到它要么使用字符串作为参数,要么使用 整数

If you look at the std::bitset constructor you will see that it either takes a string as argument, or an integer.

这意味着您的 double 值将转换为整数,并且没有标准整数类型可以容纳这么大的值,这会导致未定义的行为

That means your double value will be converted to an integer, and there is no standard integer type that can hold such large values, and that leads to undefined behavior.

如果要获取 double ,您需要做一些转换技巧才能使它起作用:

If you want to get the actual bits of the double you need to do some casting tricks to make it work:

unsigned long long bits = *reinterpret_cast<unsigned long long*>(&doubleValue);

请注意 type-punning 没有在C ++规范中定义,但是只要 sizeof(double)== sizeof(unsigned long long)会起作用。如果您希望行为明确定义,则必须遍历 char char * 的数组。

Note that type-punning like this is not defined in the C++ specification, but as long as sizeof(double) == sizeof(unsigned long long) it will work. If you want the behavior to be well-defined you have to go through arrays of char and char*.

这篇关于使用std :: bitset进行双重表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆