Created
October 19, 2023 13:34
-
-
Save FlameWolf/bc4e14087a27a3d98912f0ab465ba241 to your computer and use it in GitHub Desktop.
BigInteger.ToBase62String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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