I was reading the question convert bitset to int in c++ and thought, hey, that doesn't work, I've already tried it. But then I started trying and quickly i discovered that:
#include <bitset>
#include <iostream>
int main()
{
std::bitset<31> b31(-1);
std::bitset<32> b32(-1);
std::cout<<static_cast<int>(b31.to_ulong())<<std::endl;
std::cout<<static_cast<int>(b32.to_ulong())<<std::endl;
return 0;
}
gives the output
2147483647
-1
So, how do I cast bitsets smaller than 32 to signed integers?
CLARIFICATION: I want to cast back to signed int with the 10-base value used when constructing the bitsets preserved. "store signed ints in bitsets"
I have tried this with gcc 4.6.2, mingw32 on win 7, and the same result is obtained with c-style cast (int)
How about something along these lines:
(Inspired by Sign extending from a constant bit-width.)