Skip to content

Instantly share code, notes, and snippets.

@FlameWolf
Created October 19, 2023 13:34
Show Gist options
  • Save FlameWolf/bc4e14087a27a3d98912f0ab465ba241 to your computer and use it in GitHub Desktop.
Save FlameWolf/bc4e14087a27a3d98912f0ab465ba241 to your computer and use it in GitHub Desktop.
BigInteger.ToBase62String
using System;
using System.Collections.Generic;
using System.Numerics;
public static class BigIntegerExtensions
{
private static readonly char[] digits = new char[]
{
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z'
};
public static string ToBase62String(this BigInteger param)
{
if (param == 0)
{
return param.ToString();
}
var baseNum = 62;
var remainders = new List<char>();
var (sign, quotient) = param < 0 ? ("-", (0 - param)) : (string.Empty, param);
do
{
remainders.Insert(0, digits[(int)(quotient % baseNum)]);
quotient /= baseNum;
}
while (quotient > 0);
return $"{sign}{string.Join("", remainders.ToArray())}";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment