简体   繁体   中英

How to convert any binary string into a number?

Suppose we have given a string str="00110011" then how can we convert it into a number?

Actually, I want to get a binary string as a decimal integer.

checking your request, the convertion of the base binary to decimal, follows a example c#:

string myBinary = "00110011";

double myDecimal = 0;

int nChars = myBinary.Length-1;

int myBase = 2;

//(00110011) = (0 × 2^7) + (0 × 2^6) + (1 × 2^5) + (1 × 2^4) + (0 × 2^3) + (0 × 2^2) + (1 × 2^1) + (1 × 2^0) = 51

foreach (char c in myBinary)
{
    var myNumber = int.Parse(c.ToString());

    var exponential = Math.Pow(myBase, nChars);

    myDecimal += myNumber * exponential;

    nChars--;

}
Console.WriteLine(myDecimal);

Best Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM