Convert from bitstring to integer

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 bit Count = 8, it should return -128

The numbers are stored in the form of 2 additions. How can I do it. Are there any built-in functions that will help, so I won’t need to calculate manually.

+4
source share
2 answers

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 2nd version of the 32-bit number padding, and then just let the Convert.ToInt32 method do the magic.

+3
source

Prepare the line with 0 or 1 to make a bit-bit and do int number = Convert.ToInt16("11111111"+"10000000", 2);

+5
source