Visual C# 2005 Guide
Number Bases

Introduction

This page provides you with instructions on how to set up a program to perform conversion between different number bases.

Getting Started

You need to create a new console application in C#. The following code shows the structure of the program. The key functions have not been programmed yet. The empty functions are called 'stubs'. It is relatively easy to set your programs up like this if you used a hierarchy chart to plan what you were going to do.

class Program
{

   static void Main(string[] args)
   {
      int menItem = GetMenuChoice();
      while (menItem != 5)
      {
         string codeToConvert = GetInputString();
         switch (menItem)
         {
            case 1:
            Console.WriteLine("{0} in binary is {1}", codeToConvert, DenToBin(codeToConvert));
            WaitForInput();
            break;
            case 2:
            Console.WriteLine("{0} in denary is {1}", codeToConvert, BinToDen(codeToConvert));
            WaitForInput();
            break;
            case 3:
            Console.WriteLine("{0} in hex is {1}", codeToConvert, DenToHex(codeToConvert));
            WaitForInput();
            break;
            case 4:
            Console.WriteLine("{0} in denary is {1}", codeToConvert, HexToDen(codeToConvert));
            WaitForInput();
            break;
            }
            menItem = GetMenuChoice();
         }
   }

   static int GetMenuChoice()
   {
      //function to display menu and read in user choice
      Console.Clear();
      Console.WriteLine("Binary And Hex Conversion Program");
      Console.WriteLine("*********************************");
      Console.WriteLine();
      Console.WriteLine("1. Denary To Binary");
      Console.WriteLine("2. Binary To Denary");
      Console.WriteLine("3. Denary To Hex");
      Console.WriteLine("4. Hex To Denary");
      Console.WriteLine("5. Quit Program");
      int menChoice = System.Convert.ToInt32(Console.ReadLine());
      return menChoice;
   }

   static string GetInputString()
   {
      Console.WriteLine();
      Console.Write("Enter the value to convert: ");
      return Console.ReadLine();
   }

   static string DenToBin(string inputString)
   {
      return "";
   }

   static int BinToDen(string inputString)
   {
      return 0;
   }

   static string DenToHex(string inputString)
   {
      return " ";
   }

   static int HexToDen(string inputString)
   {
      return 0;
   }

   static void WaitForInput()
   {
      Console.WriteLine();
      Console.WriteLine("Press any key to continue");
      Console.ReadLine();
   }

}

Conversion Algorithms

Th following pseudocode and explanations should help you to write fill in the missing code in the program.

When you implement an algrithm from someone else's pseudocode, the easy part of the exercise is translating the programming structures that see into the syntax demande by the C# compiler. The key is to also try to understand how the algorithm achieves the result that it does. Writing a program flowchart can help you visualise things better. Dry-running helps to show you how values stored in the variables change in the program and come to equal the desired result.

Conversion From Denary To Binary

Declare string array bits[16] = new string[16]
Declare int index← 0
Declare int thisbit← 0
Declare int num ← Convert inputString to int32
Do
   thisbit ← num Mod 2
   num ← (int) num/2
   bits[index] ← ConvertToString(bit).Trim()
   index ← index + 1
While num is not equal to 0
Array.Reverse(bits)
Declare string myAnswer ← String.Join("", bits)
return myAnswer

Conversion From Binary To Denary

Declare int myAnswer ← 0
Declare int thisBit ← 0
Declare int thisPlaceValue ← 0
Declare string reversed ← 0
For i ← inputString.Length - 1 To 0 Step - 1
   reversed ← reversed + inputString.SubString(i , 1)
End For
For i ← 0 To inputString.Length - 1
   thisBit ← Convert To Int32 (reversed.SubString(i , 1)
   thisPlaceValue ← (int) Math.Pow (2.0f, (double) i)
   myAnswer ← myAnswer + (thisBit * thisPlaceValue)
End For
return myAnswer

Conversion To And From Hex

The functions should mirror the ones above.

When converting to Hex, instead of dividing by 2, divide by 16. You will need to examine the result in order to store the correct character (0 - 9 + A, B, C, D, E, F) in the myAnswer String (use if or switch statements).

When converting from Hex, instead of calculating the columns place value by finding the power of 2, use a power of 16. You will need to convert the string to an integer. You will need to convert the digit into an integer by checking whether what it currently contains.

You may find it useful to write a function to convert a single digit from hex to decimal and another to convert the other way.

Adding Conversions Between Hex And Binary

The program so far should convert successfully between denary and either hex or binary. The two missing features are clearly the conversions between hex and binary.

It's relatively easy to program these. For each of the sixteen permissibles digits in hex (0-15), there is a single 4 bit binary pattern. The easiest way to program the conversion from hex to binary is to do it is to convert a character at a time. You write a function that accepts a hex character and returns the equivalent 4 bit binary pattern. You write another function which calls this for each of the characters in the input string, adding them onto a string until the whole number has been represented.

To convert back again, do the opposite.

You may have spotted that a quicker solution is to call the functions that you already have. Say the user inputs a hex number. You could convert it to denary using the functions that you have made and then call the denary to binary function to do the business for you again. The main reason to still write the additional functions is so that you know how to do it.

Going Even Further

If you think about it carefully, the algorithm you have used to convert from denary to binary can be generalised. The number 2 that appears in the do loop is a number 2 because that is the number of the base to which we are converting. If that were a parameter of the function, you could convert to whatever base was supplied when the function was called.

If you stick at base 9 and below, it's fairly easy to make the adjustment. Number bases are in use in all sorts of ways and for all sorts of reasons. It is interesting to research the reasons why. Many of the number bases reveal patterns in number that can't be seen in denary representations of number. You can assume that the Arabic numerals will be used for values 0-9 and that the upper case Latin letters A-Z would be used for columns in bases up to 36. Thereafter you use lower case letters and call it quits when you run out of characters.

If Really Like Maths

You could adapt the program to convert a job lot of numbers for you in one go. Counting is easier - but what do prime numbers look like in other bases? What about perfect numbers, square numbers, triangular numbers and so on? You have seen how the representation of binary fractions relates to denary. The same relationship can be assumed for all other bases too. There are some benefits to being able to represent fractions using a finite system.

Once you realise that you can use the built-in data types to represent numbers in all sorts of bases, you start to realise that the important thing is to store the correct values for the digits in each column. That can mean using a string or even an array of strings. It also means that, by using arrays or strings you can work with denary numbers in some interesting ways. If you program the computer to perform denary calculations on a column-by-column basis, the way you would on paper, you can carry over numbers the way you normally would. It is laborious by hand but once programmed, the computer is limited mainly by the maximum size of a string and the complexity and number of calculations it is asked to do. You could make a program that works out 1000000! and returns a string representation of the answer - a number far bigger than that you can work with in a numeric data type.