Reputation: 277
How can I convert the number 1234 to its base 10, 194 using code ?
string toBase10 = Convert.ToString(1234, 10);
Console.WriteLine(toBase10);
Upvotes: 2
Views: 1263
Reputation: 11228
Another LINQ solution:
static int ConvertFromBase(int num, int @base)
{
return num.ToString().Reverse()
.Select((c, index) => (int)Char.GetNumericValue(c) * (int)Math.Pow(@base, index))
.Sum();
}
Console.WriteLine(ConvertFromBase(1234, 5)); // 194
Upvotes: 0
Reputation: 8025
The simple way, use Linq:
static int ConvertFromBase5(string number)
{
return number.Select(digit => (int)digit - 48).Aggregate(0, (x, y) => x * 5 + y);
}
Use:
Console.Write(ConvertFromBase5("1234"));
Upvotes: 2
Reputation: 109537
How about this?
public static long FromBase(long value, int @base)
{
string number = value.ToString();
long n = 1;
long r = 0;
for (int i = number.Length - 1; i >= 0; --i)
{
r += n*(number[i] - '0');
n *= @base;
}
return r;
}
I made it long
to handle bigger values. You could make it int
if you wanted.
You could use it like this:
Console.WriteLine(FromBase(1234, 5)); // Prints "194"
Or if you wanted a string, just use ToString()
on it.
var asString = FromBase(1234, 5).ToString();
It won't handle bases above 10 - but you can't hold numbers above base 10 in an int
or long
anyway - In fact, it's odd to do that for any base other than 10. Usually you'd use a string
to avoid accidentally using those numbers as if they were base 10.
Upvotes: 1