Recipe1.7.Converting a Number in Another Base to Base10


Recipe 1.7. 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 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 value expressed in base2, base8, base10, and base16 only. They do not allow for converting a value to a string expressed in any other base types than base10. However, the ToString methods on the various numeric types do allow for this conversion.

See Also

See the "Convert Class" and "Converting with System.Convert" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net