Search code examples
c++bitset

Convert signed short with bitset


I want convert string with 0 and 1 to signed short. This work, but negative numbers I have wrong values. I think, problem is converting from unsigned to signed. How can fix that? Example: 971 is 971, 425 is 425 , -122 is 3974 , -394 is 3702 , -2032 is 2064

bitset<12> b(binary);//binary is string of 0 and 1
 cout<<(signed short)b.to_ulong()<<"\n";

Solution

  • In a 16 bit signed integer, negative numbers are represented as:

    1xxx xxxx xxxx xxxx
    

    positive numbers as:

    0xxx xxxx xxxx xxxx
    

    Example:

    0000 1111 1000 0110 => 3974
    

    What you need is a 12 bit integer, where negative numbers are represented as:

    .... 1xxx xxxx xxxx
    

    Example:

    .... 1111 1000 0110 => -122
    

    You could do something like this:

    #include <iostream>
    #include <bitset>
    #include <string>
    
    using namespace std;
    
    struct C {
        signed short b : 12; // 12 bit integer
    };
    
    int main() {
        string binary = "111110000110"; // 3974
        bitset<12> b(binary);
    
        struct C c = { static_cast<signed short>(b.to_ulong()) };
    
        cout << c.b << "\n"; // prints -122
    }