Search code examples
c++stdbitsetstd-bitset

Convert bitset<a> to signed int, with a<32>


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)


Solution

  • How about something along these lines:

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

    (Inspired by Sign extending from a constant bit-width.)