Reputation: 1443
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?Upvotes: 1
Views: 2533
Reputation: 150
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.
Upvotes: 2
Reputation: 1861
Yes you are correct convertTo(28, 16) == c1
The loop in the code should be:
while (value != 0)
{
index = value / radix; // implicit integer division
value = value % radix;
result += alphabet[index].ToString();
}
As to your second question I believe that to be correct also - that's more for a mathematics expert to verify though.
Upvotes: 1
Reputation: 7163
Yes, that code needs to reverse the output. Below are the results when I ran that code in Visual Studio 2015, and the corresponding output in the Locals window.
var ret1 = convertTo(28, 16);
var ret2 = convertTo(28, 10);
var ret3 = convertTo(10, 10);
ret1 "c1" string
ret2 "82" string
ret3 "01" string
Upvotes: 1