Search code examples
c++std-bitset

Converting a bitset to signed


I have a std::bitset<32> and I want to isolate the right 16 bits and output those bits as if they were a signed number. I also am going to want to output the entire 32 bit thing as a signed number down the road. However, Bitset does not support a signed int to_string().

for example 1010000000100001 1111111111111111:

I want one output to be:

-1608384513 for the whole sequence

-1 for the right 16 bits.

Any slick ways of converting them?


Solution

  • To get a 16-bit number you can use to_ulong(), drop the upper 16 bits, and reinterpret as int16_t.

    Similarly, for a signed 32-bit number you can call to_ulong(), and reinterpret as a signed int32_t.

    std::bitset<32> b("10100000001000011111111111111111");
    int16_t x16 = (int16_t)(b.to_ulong() & 0xFFFF);
    int32_t x32 = (int32_t)b.to_ulong();
    cout << x16 << endl;
    cout << x32 << endl;
    

    Demo.