Convert bits <a> to signed int, with <32
I read the question of converting bits to int in C ++ and thought this did not work, I already tried. But then I started trying and quickly found 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 way
2147483647
-1
So, how do I pass bits smaller than 32 to signed integers?
CLARIFICATION: I want to return back to a signed int with a 10-base value used when constructing the stored bits. "store signed ints in bits"
I tried this with gcc 4.6.2, mingw32 on win 7, and the same result is obtained with c-style cast (int)
+4
3 answers
How about something in this direction:
#include <bitset>
#include <iostream>
template<std::size_t B>
long bitset_to_long(const std::bitset<B>& b) {
struct {long x:B;} s;
return s.x = b.to_ulong();
}
int main()
{
std::bitset<31> b31(-1);
std::bitset<32> b32(-1);
std::cout << bitset_to_long(b31) << std::endl;
std::cout << bitset_to_long(b32) << std::endl;
return 0;
}
( , .)
+2