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

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 and returns this number displayed as base10.

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 a base type for this number. Unfortunately, these methods convert from base2, base8, base10, and base16 only to a value of base10. They do not convert a value to any other base types.

See Also

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



C# Cookbook
C# 3.0 Cookbook
ISBN: 059651610X
EAN: 2147483647
Year: 2003
Pages: 315

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