20.3. Converting a Number in Another Base to Base10
Problem
You have a string containing a number in base2 (binary), base8 (octal), base10 (decimal), or base16 (hexadecimal). You need to convert this string to its equivalent integer value and display it in base10.
Solution
To convert a number in another base to base10, use the overloaded static Convert.ToInt32 method on the Convert class:
string base2 = "11"
string base8 = "17";
string base10 = "110";
string base16 = "11FF";
Console.WriteLine("Convert.ToInt32(base2, 2) = " +
Convert.ToInt32(base2, 2));
Console.WriteLine("Convert.ToInt32(base8, 8) = " +
Convert.ToInt32(base8, 8));
Console.WriteLine("Convert.ToInt32(base10, 10) = " +
Convert.ToInt32(base10, 10));
Console.WriteLine("Convert.ToInt32(base16, 16) = " +
Convert.ToInt32(base16, 16));This code produces the following output:
Convert.ToInt32(base2, 2) = 3 Convert.ToInt32(base8, 8) = 15 Convert.ToInt32(base10, 10) = 110 Convert.ToInt32(base16, 16) = 4607
Discussion
The static Convert.ToInt32 method has an overload that takes a string containing a number and an integer defining the base of this number. This method then converts the numeric string into an integer, Console.WriteLine, and then converts the number to base10 and displays it.
The other static methods of the Convert class, such as ToByte, ToInt64, and ToInt16, also have this same overload, which accepts a number as a string and the base in which this number is expressed. Unfortunately, these methods convert from a string ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access