1

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?

Raphnika
  • 62
  • 9
  • You're casting binary values to char - you aren't converting the binary values to characters in the range 'A' to 'F' correctly. – Matthew Watson Aug 22 '16 at 14:45
  • BTW, you can get rid of the array of strings approach and just do it all in one string. You'll need a Reverse of string method, though. See http://stackoverflow.com/a/228060/49251. So you can do it with output declard `string Output = ""`. Then you add to it via `Output += c.ToString();`, etc. Then referse the string and have the method return a string. – DWright Aug 22 '16 at 15:25
  • @Raphnika: I see you edited your question to re-include the "thanks" at the end -- the general consensus around here is to omit any kind of "thanks" from your posts. Think of questions and answers here as technical writing -- while it may seem harsh, there's just no point. Thank your answerer(s) by accepting or upvoting when appropriate. – Cᴏʀʏ Aug 22 '16 at 15:39
  • @Cory Alright... changed it back – Raphnika Aug 23 '16 at 05:53

1 Answers1

2

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'.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • Allright! Got it. Thank you very much for your help and have a nice day! – Raphnika Aug 22 '16 at 14:53
  • 1
    I know this was an assignment, but in an actual .NET production application, you could and should replace your entire method with `15555.ToString("X");`. You wouldn't want to recreate the wheel, though your professor probably wants to you to do it the hard way. – Cᴏʀʏ Aug 22 '16 at 14:59
  • @Cory yeah... he wants us to understand how everything works. – Raphnika Aug 22 '16 at 15:04