C# Base62 Sample Code

Find out how to implement Base62 encoding and decoding in C# with sample code for real-world applications.

using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;

public class Base62
{
    private const string BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    public static string Encode(byte[] input)
    {
        if (input.Length == 0)
        {
            return string.Empty;
        }

        BigInteger value = new BigInteger(input);
        StringBuilder result = new StringBuilder();

        while (value > 0)
        {
            value = BigInteger.DivRem(value, 62, out BigInteger remainder);
            result.Append(BASE62[(int)remainder]);
        }

        foreach (byte b in input)
        {
            if (b == 0)
            {
                result.Append(BASE62[0]);
            }
            else
            {
                break;
            }
        }

        char[] resultArray = result.ToString().ToCharArray();
        Array.Reverse(resultArray);
        return new string(resultArray);
    }

    public static byte[] Decode(string input)
    {
        if (input.Length == 0)
        {
            return new byte[0];
        }

        BigInteger value = BigInteger.Zero;
        foreach (char c in input)
        {
            value = value * 62 + BASE62.IndexOf(c);
        }

        byte[] bytes = value.ToByteArray();
        if (bytes[0] == 0)
        {
            bytes = bytes[1..];
        }

        int leadingZeroes = 0;
        foreach (char c in input)
        {
            if (c == BASE62[0])
            {
                leadingZeroes++;
            }
            else
            {
                break;
            }
        }

        byte[] result = new byte[leadingZeroes + bytes.Length];
        Array.Copy(bytes, 0, result, leadingZeroes, bytes.Length);
        return result;
    }

    public static void Main(string[] args)
    {
        // Encoding example
        string input = "回□〓≡╝╚╔╗";
        string encoded = Encode(Encoding.UTF8.GetBytes(input));
        Console.WriteLine("Encoded: " + encoded);

        // Decoding example
        string decoded = Encoding.UTF8.GetString(Decode(encoded));
        Console.WriteLine("Decoded: " + decoded);
    }
}
Base62 Sample Code