Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 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 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.

like image 943
softwarematter Avatar asked Feb 24 '23 00:02

softwarematter


1 Answers

Prepend the string with 0's or 1's to make up to the bitCount and do int number = Convert.ToInt16("11111111"+"10000000", 2);

like image 100
Nemo Avatar answered Mar 08 '23 02:03

Nemo