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
source share
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

, , OR , 1, :

const int sz = 15;
std::bitset<sz> b(-1);
int num = static_cast<int>(b.to_ulong());
if (b[sz-1]) {
    int mask = (1<<sz)-1;
    num |= ~mask;
}
std::cout << num << std::endl;

(1<<sz) sz. (1<<sz)-1 sz-1, 1 s. ~ , .

-

+1

#define BITLEN 31
#define SHIFT_AMOUNT (sizeof(int)*CHAR_BIT - BITLEN)

std::bitset<BITLEN> b31(-1);
int v = (static_cast<int>(b31.to_ulong()) << SHIFT_AMOUNT) >> SHIFT_AMOUNT;
std::cout << v << std::endl;
0

All Articles