使用bitset将二进制数转换为十进制数

时间:2014-05-08 14:17:32

标签: binary decimal bitset

#include<cstdio>
#include<bitset>
#include<iostream>
#include<cmath>
using namespace std;
int main(){
    bitset<5> num(-5);
    if(num[0])
        cout<<(num.to_ulong()-pow(2,5));// cout<<(num.to_ulong()-32);
    else    
        cout<<num.to_ulong();
    return 0;
}

在上面的代码中,如果我使用注释中给出的代码,它会打印一个不同的数字(4294967291)。这里发生了什么?

1 个答案:

答案 0 :(得分:0)

您必须将ulong减法的结果转换为带符号的长整数:

(((long)num.to_ulong())-32)