Exercises in this lecture   previous -- Keyboard shortcut: 'p'        Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home      

Exercise 2.3
Hexadecimal numbers

In this exercise we will write a program that can convert between decimal and hexadecimal notation of numbers. Please consult the focus boxes about hexadecimal numbers in the text book version if you need to.

You might expect that this functionality is already present in the C# libraries. And to some degree, it is.

The static method ToInt32(string, Int32) in class Convert converts the string representation of a number (the first parameter) to an arbitrary number system (the second parameter). Similar methods exist for other integer types.

The method ToString(string) in the struct Int32, can be used for conversion from an integer to a hexadecimal number, represented as a string. The parameter of ToString is a format string. If you pass the string "X" you get a hexadecimal number.

The program below shows examples:

using System;
class NumberDemo{
  public static void Main(){
     int i = Convert.ToInt32("7B", 16);     // hexadecimal 7B (in base 16) -> 
                                            // decimal 123 
     Console.WriteLine(i);                  // 123

     Console.WriteLine(123.ToString("X"));  // decimal 123 -> hexadecimal 7B 

Now, write a method which converts a list (or array) of digits in base 16 (or more generally, base b, b >= 2) to a decimal number.

The other way around, write a method which converts a positive decimal integer to a list (or array) of digits in base 16 (or more generally, base b).

Here is an example where the requested methods are used:

  public static void Main(){
    int r = BaseBToDecimal(16, new List{7, 11});  // 7B  -> 123 
    List s = DecimalToBaseB(16, 123);             // 123 -> {7, 11} = 7B
    List t = DecimalToBaseB(2, 123);              // 123 -> {1, 1, 1, 1, 0, 1, 1 } = 
                                                       // 1111011
    foreach (int digit in s) Console.Write("{0} ", digit);  Console.WriteLine();
    foreach (int digit in t) Console.Write("{0} ", digit);