Reputation: 2614
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";
Upvotes: 1
Views: 865
Reputation: 17999
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
}
Upvotes: 2
Reputation: 676
The values you are getting are correct for a cast from a 12-bit signed integer to a 12-bit unsigned integer.
For example, -122 as a signed 12-bit integer would be represented as 111110000110 in binary, which is also the binary representation for 3974 as an unsigned 12-bit integer.
What were you expecting?
Edit
I see now that you are trying to convert to signed short for output. Consider that a short is 16-bits whereas your bitset is 12 bits filled into an unsigned long. The function to_ulong does not perform sign extension (it has no context that would enable it to determine if sign extension is necessary and thus clears the most significant bits beyond what is represented in the bitset), and so you are getting what your bit pattern would represent were it an unsigned number.
Upvotes: 1