Raphnika
Raphnika

Reputation: 62

Writing a base conversion tool and having trouble with hexadecimal

My current assignment is to write a converter to different systems. Converting to binary was no problem, but I am having some troubles with hexadecimal. Here is my code:

    public string[] ConvertInput(int pInput, int pBase)
    {
        List<string> Output = new List<string>();
        int Tmp = pInput;
        int TmpBin;

        for (int i = 0; Tmp > 0; i++)
        {
            TmpBin = Tmp % pBase;
            Tmp = Tmp / pBase;
            if (TmpBin >= 10)
            {
                char c = (char)TmpBin;
                Output.Add(c.ToString());
            }
            else
            {
                Output.Add(TmpBin.ToString()); 
            }
        }

        string[] OutArray = Output.ToArray();

        Array.Reverse(OutArray);

        return OutArray;
    }

So if I try to convert the number 15555 to hexadecimal, it should give 3cc3 back, but what it does is return 3\f\f3.

What did I do wrong?

Upvotes: 1

Views: 37

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109547

Instead of this:

if (TmpBin >= 10)
{
    char c = (char)TmpBin;
    Output.Add(c.ToString());
}

Do this:

if (TmpBin >= 10)
{
    char c = (char)('A' + (TmpBin - 10));
    Output.Add(c.ToString());
}

In your version, you are casting the decimal values 10, 11, 12 etc directly to characters, and (for example) the character with code 10 is line feed, not 'A'.

Upvotes: 2

Related Questions