Wednesday, November 04, 2009

Method for converting a number to base in C#.net

public static string ConvertToBase(int num, int nbase)
{
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

// check if we can convert to another base
if (nbase <> chars.Length)
return "";

int r;
String newNumber = "";

// in r we have the offset of the char that was converted to the new base
while (num >= nbase)
{
r = num % nbase;
newNumber = chars[r] + newNumber;
num = num / nbase;
}
// the last number to convert
newNumber = chars[num] + newNumber;

return newNumber;
}

No comments: