Search code examples
c#radixbase-conversion

C# base converter


I stumbled on this method which should do a base convert from a 10 base to radix base, so for example if I pass 28, 16 it should return 1c which is the hexadecimal representation of the decimal 28

private static string convertTo(long value, int radix)
{
    char[] alphabet = "0123456789abcdefghijklmnopqrstuv".ToCharArray();
    string result = "";

    if (value < radix) {
        return alphabet[value].ToString();
    }

    long index;
    while (value != 0)
    {
        index = value % radix;
        value = Convert.ToInt64(Math.Floor(value / radix));  
        result += alphabet[index].ToString();
    }
    return result;
}

I'm rewriting that part of the program in PHP. By reading the code above, and predicting output manually, it returns c1 where it should return 1c for 28, 16

My finding is that this method returns a reversed representation of string in a given base, c1 instead of correctly 1c

Because I do not have a C# compiler I could not verify my findings.

So here are my two questions:

  1. Are my calculations right that the above method calld with 28, 16 returns c1?
  2. I suppose symbols (digits/alphabets), in any base, are written so that base exponents decreases by 1 as we go from left to write, so for example in decimal representation 312 means 300 (3 * 10 ^ 2) + 10 (1 * 10 ^ 1) + 2 (2 * 10 ^ 0).. is that absolutely always correct?

Solution

    1. For me, yes. the snippet in C# (as it is) should return C1, instead of 1C. You will need to reverse the string result before returning it. (or use instead something like result = string.Concat(alphabet[index].toString()); when creating the result string)

    2. That's correct. It also works in all the other bases, i.e. if we take your example (28), you'll have :

    28 = 2 * 10^1 + 8 * 10^0 (base 10)

    28 = 1 * 16^1 + 12 * 16^0 (base 16) = 1C

    28 = 3 * 8^1 + 2 * 8^0 (base 8) = 32

    etc, etc.