Reputation: 29178
I need a function like
int GetIntegerFromBinaryString(string binary, int bitCount)
if binary = "01111111" and bitCount = 8, it should return 127
if binary = "10000000" and bitCount = 8, it should return -128
The numbers are stored in 2's complement form. How can I do it. Is there any built in functions that would help so that I needn't calculate manually.
Upvotes: 4
Views: 4232
Reputation: 13196
here you go.
static int GetIntegerFromBinaryString(string binary, int bitCount)
{
if (binary.Length == bitCount && binary[0] == '1')
return Convert.ToInt32(binary.PadLeft(32, '1'),2);
else
return Convert.ToInt32(binary,2);
}
Convert it to the 2-s complement version of a 32 bit number, then simply let the Convert.ToInt32 method do it's magic.
Upvotes: 3
Reputation: 25418
Prepend the string with 0's or 1's to make up to the bitCount and do
int number = Convert.ToInt16("11111111"+"10000000", 2);
Upvotes: 5