0

I can't figure out why my binary to denary number converter doesn't work. I need a simple solution to demonstrate to GCSE Computer Science students. please help:

static void Main(string[] args)
{
    string binaryNumber;
    int[] placeValues = { 128, 64, 32, 16, 8, 4, 2, 1 }; 
    // Array stores place values of the digits
    int denaryNumber = 0;

    Console.WriteLine("Please enter an 8-bit binary number: ");
    binaryNumber = Console.ReadLine();

    // The digits will now be multiplied by the place values
    for (int index = 0; index < binaryNumber.Length; index++)
    {
        denaryNumber = denaryNumber + 
        (Convert.ToInt32(binaryNumber[index]) * placeValues[index]);
    }
    Console.WriteLine("\n" + binaryNumber + " = " + denaryNumber);
    Console.ReadKey();
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

2 Answers2

0

When working with strings like

 "011001"

you should subtract '0' to get integer digit: 1 == '1' - '0', while Convert.ToInt32('1') != 1, i.e.

binaryNumber = Console
  .ReadLine()
  .Trim()                            // Let's be nice and remove (white) spaces 
  .PadLeft(placeValues.Length, '0'); // What if "011" is the input?

for (int index = 0; index < binaryNumber.Length; index++)
{
    denaryNumber += (binaryNumber[index] - '0') * placeValues[index];
}

Be careful with indexes: you should have binaryNumber being exactly the same length as placeValues (the very reason I've added PadLeft).

Edit: In real life we do conversion as simple as

int denaryNumber = Convert.ToInt32(binaryNumber, 2);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0
Convert.ToInt32(binaryNumber[index])

does not do what you want. It gives you the internal representation (ASCII value) of the character, not the numerical value represented by it. Use

(int)Char.GetNumericValue(binaryNumber[index])

instead. Alternatively, you could subtract '0'

binaryNumber[index] - '0'
adjan
  • 13,371
  • 2
  • 31
  • 48