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:
(3 * 10 ^ 2)
+ 10 (1 * 10 ^ 1)
+ 2 (2 * 10 ^ 0)
.. is that absolutely always correct?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)
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.