0
#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;
}

In the code above if I use the code given in the comments it prints a different number(4294967291). What is going on here?

billyjayan
  • 27
  • 8

1 Answers1

0

you have to cast the result of the ulong subtraction to a signed long:

(((long)num.to_ulong())-32)
collapsar
  • 17,010
  • 4
  • 35
  • 61
  • Actually, it works fine without that; it is the commented portion that does not work, even though 2^5 and 32 are both the same value – billyjayan May 08 '14 at 14:32
  • That totally worked! Was that because subtraction of a number from an unsigned long always produces unsigned numbers? – billyjayan May 08 '14 at 15:00
  • the actual conversion rules are defined in the language specs. in that particular case, the literal's type is less constrained (effectively compatible with all signed and unsigned integer types) than that of the function result (unsigned long), so i guess that's the base of the decision for the auto-cast. but once again, there are specific rules which you can look up in the lagugae spec. – collapsar May 08 '14 at 15:05