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

Exercise solution:
Hexadecimal numbers


Here is a solution which provides general methods to and from base B:

using System;
using System.Collections.Generic;

class NumberSystems{

  public static int BaseBToDecimal(int B, List<int> digits){
    int result = 0;
    for(int i = 0; i < digits.Count; i++)
       result += digits[digits.Count-i-1] * (int)Math.Pow(B,i);
    return result;
  }

  public static List<int> DecimalToBaseB(int B, int i){
    List<int> result = new List<int>();
    int j = i;
    do{
      result.Insert(0, j % B);
      j = j / B;
    }
    while(j > 0);
    return result;
  }

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

The Pow method is a static method in class System.Math. Math.Pow(a, b) raises a to the power of b. Example: Math.Pow(2, 3) = 2 * 2 * 2. Pow works on doubles. Therefore we cast the result to an integer.

Notice that the operator / is an integer division operator when applied on values of type int.

The expressions i % j returns the remainder of the integer division i / j.

For details on List<T> for some type T (here int) please consult the slide overview of the class List.