Kéven Bastien
Kéven Bastien

Reputation: 23

Convert hexadecimal to decimal

I'm currently building a converter in C#. My program is converting from/to Decimal, Binary and Hexadecimal. My problem is that in some specific cases the result is not correct.

Examples:

FFFFF (hexa) to Decimal = 148575 (Real answer: 1048575)

20000 (decimal) to Decimal = 20 (Real answer: dont need a calculator :P)

Also I can't use any Convert.ToString as it is for school and my teacher asked us to manipulate the variables and play with functions.

I think my convertToString() function causes the problem of losing zeros somewhere.

private string convertToString(int value)
{
    string result = "";
    string tmp = "";
    int y = 0;

    while (value != 0) {
        int valeur = value;
        y = 0;
        while (valeur > 9) {
            valeur = valeur / 10;
            y++;
        }
        switch (valeur) {
            case 0:
                tmp = "0";
                break;
            case 1:
                tmp = "1";
                break;
            case 2:
                tmp = "2";
                break;
            case 3:
                tmp = "3";
                break;
            case 4:
                tmp = "4";
                break;
            case 5:
                tmp = "5";
                break;
            case 6:
                tmp = "6";
                break;
            case 7:
                tmp = "7";
                break;
            case 8:
                tmp = "8";
                break;
            case 9:
                tmp = "9";
                break;
        }
        value = (int)(value - (valeur * Math.Pow(10, y)));
        result = result + tmp;
    }

    if (y != 0) {
        result = result + "0";
    }
    return result;
}

Thank you in advance.

Upvotes: 2

Views: 4289

Answers (5)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112342

The problem is that you create confusion with two names meaning the same in English and French: value / valeur;

You would calculate the decimal places like this

string result = "";
bool minus = false;
if (value == 0 ) {
    result = "0";
} else {
    // Begin the string with a minus (`-`) if value is negative
    // and continue the conversion with a positive value.
    if (value < 0) {
         minus = true;
         value = - value;
    }

    // Add decimals to the result as long as the remaining number is not zero.
    while (value > 0) { 
        // Get last decimal using the modulo operator
        int lastDecimal = value % 10;

        // Prepend the decimal to the result after having converted it to a character
        result = (char)('0' + lastDecimal) + result;

        // Divide the value by 10. Integer division!
        value = value / 10;
    }
    if (minus) {
        result = "-" + result;
    }
}

Upvotes: 0

markmuetz
markmuetz

Reputation: 9664

This is a good example of when you have one known good function, and you want to test your own implementation against it. How might this code:

        for (int i = 0; i < 100000; i++)
        {
            if (i.ToString() != ConvertToString(i))
            {
                Console.WriteLine(i);
                ConvertToString(i);
            }
        }

help you? First of all, it will tell you which numbers your method doesn't work for. Second, you can attach the debugger to the WriteLine line, and then step through the second run through of your method.

Here's an example that works using Math.Log10 and Math.Pow. Step through it with the debugger to see why it doesn't drop any zeros (it did at first, but it was obvious why after using the seeing which cases is failed for, then using the debugger).

    static string ConvertToString(int value)
    {
        string result = "";
        int power = (int)Math.Log10(value);
        while (power >= 0)
        {
            int nextLowestPowerOfTen = (int)Math.Pow(10, power);
            int lowestMultipleOfPowerOfTen = (int)(value / nextLowestPowerOfTen);
            result += lowestMultipleOfPowerOfTen;
            value -= lowestMultipleOfPowerOfTen * nextLowestPowerOfTen;
            power--;
        }
        return result;
    }

Upvotes: 0

Jason Williams
Jason Williams

Reputation: 57902

Take a simple number like value=123 or value=103 and execute the code step by step.

You can do this using debugger single stepping and watching the values of the variables, but if you want to really learn how the code works, use your own brain as the CPU and see if you can work through it on a piece of paper.

As you step through the operations you will be able to see what happens to the numbers and can watch the exact moment wheer it goes wrong, in order to come to an understanding of what is happening.

Upvotes: 2

Jeremy Thompson
Jeremy Thompson

Reputation: 65554

It looses 0's here:

while (valeur > 9) { valeur = valeur / 10; y++; }

You keep dividing the number until its less than 9, incrementing the count using the variable y.

Then you cant get it back using this: value = (int)(value - (valeur * Math.Pow(10, y)));

I dont know what the point of this function is, I'm guessing ToString without using the inbuilt function, if so here is one way using a StringBuilder and Int Array:

private string convertToString(int value)
{
    int[] valueAsArray = digitArr(value);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < valueAsArray.Length; i++)
    {
        sb.Append(valueAsArray[i]);
    }
    return sb.ToString();
}

public static int[] digitArr(int n)
{
    if (n == 0) return new int[1] { 0 };
    var digits = new List<int>();

    for (; n != 0; n /= 10)
    {
        digits.Add(n%10);
    }
    var arr = digits.ToArray();
    Array.Reverse(arr);
    return arr;
}

I would urge you to fix your own function that way when your teacher checks here he see's you put in effort and worked it out using the debugger as phong mentioned...

Upvotes: 0

phoog
phoog

Reputation: 43046

I would advise you to step through your code in the debugger, examining the flow of control. You should also examine values of the variables using the Locals window. You will see where the algorithm you created is different from the algorithm you thought you created.

Another useful technique is to break the existing method into smaller methods that perform simpler parts of the task. Give the methods names that describe the part of the task they're doing. This makes it easier to change your logic (for example, when you learn about a better way to convert digits to characters!). Good luck.

Upvotes: 3

Related Questions