Convert decimal numbers to any base (C#)

You can use this little function to convert a decimal to any base. I use it for compacting large numbers.

public static class BaseConverter
{
    public static string Encode(BigInteger value, int @base=0, string chars="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    {
        if (@base <= 0) @base = chars.Length;
        var sb = new StringBuilder();
        do
        {
            int m = (int)(value % @base);
            sb.Insert(0, chars[m]);
            value = (value - m) / @base;
        } while (value > 0);
        return sb.ToString();
    }
}

Or you can use it to make a nice GUID:

private static BigInteger UnsignedBigInt(byte[] bytes)
{
    if ((bytes[bytes.Length - 1] & 0x80) != 0) Array.Resize(ref bytes, bytes.Length + 1);
    return new BigInteger(bytes);
}

private static string GetUniqueFileName(string extension)
{
    return BaseConverter.Encode(UnsignedBigInt(Guid.NewGuid().ToByteArray()), 0, "0123456789abcdefghijklmnopqrstuvwxyz_-") + extension;
}
Posted in

One thought on “Convert decimal numbers to any base (C#)

  1. Thanks! needed the base converter for my application – sure beats having to do it on my own… especially with time constraints on projects. works great!

Leave a Reply

Your email address will not be published. Required fields are marked *