
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
10
|
Chapter 1: Numbers and Enumerations
The GetLowWord method is modified as shown here:
public static short GetLowByte(short shortValue)
{
return (short)(shortValue & (short)0xFF);
}
1.7 Converting a Number in Another Base to Base10
Problem
You have a string containing a number in base2 (binary), base8 (octal), base10 (deci-
mal), or base16 (hexadecimal). You need to convert this string to its equivalent inte-
ger 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 ...