Below are a much simpler implementation with explanation.
I use bit manipulation to convert maximum 32-char binary string into 32-bit signed integer. The following example of input is 24-char binary string. Perhaps many have overlooked the fact that character "0" and "1" has respective ASCII code (48 and 49) which can be differentiated by 0x01. "0" (ASCII code 48) has binary number 0011 0000 "1" (ASCII code 49) has binary number 0011 0001 So whenever I use bitwise operator AND (& 1) with the character in the binary string, I will get value 1 exactly for "1" (ASCII 49) and value 0 exactly for "0" (ASCII 48). The remaining part in the code snippet is rather self-explanatory. For example, binary number (G) is keep ORing itself starting from rightmost character of the binary string, so if i=0, it will look for rightmost character, and will shift left (SHL) 0 bit. If i=1, it will look for second-rightmost character, and will shift left (SHL) 1 bit until it reaches all 32-bit. While looping, it will ORing (G += ...) with the previous binary number.
CODE
string binaryString = "011100100111001001110011";
int G = 0;
for (int i = 0; i < binaryString.Length; i++)
G += (int)((binaryString[binaryString.Length - (i + 1)] & 1) << (i % 32));
Console.WriteLine(G); //7500403
Or extended version: with function to convert back binary number (G) to binary string:
CODE
string binaryString = "011100100111001001110011";
int G = 0;
for (int i = 0; i < binaryString.Length; i++)
G += (int)((binaryString[binaryString.Length - (i + 1)] & 1) << (i % 32));
Console.WriteLine(G); //7500403
binaryString = string.Empty;
for (int i = 31; i >= 0; i--)
binaryString += (char)((((uint)G & (1 << (i % 32))) >> (i % 32)) | 48);
Console.WriteLine(binaryString); //00000000011100100111001001110011
And....
This code snippet will count the number of bit (set to 1) in 32-bit unsigned integer:
CODE
uint G = 8501; //10 0001 0011 0101
uint g = 0;
for (int i = 0; i < 32; i++)
{
g += (G << (31 - (i % 32))) >> 31;
}
Console.WriteLine(g); //6
Enjoy!
This post has been edited by Mussel: Dec 17 2019, 01:46 PM