namespace ActivityPub.Utils;
///
/// Helper class for converting numbers to and from Base36 strings
/// https://stackoverflow.com/a/35004409
///
public class Base36
{
private static readonly char[] BaseChars =
"0123456789abcdefghijklmnopqrstuvwxyz".ToCharArray();
private static readonly Dictionary CharValues = BaseChars
.Select((c, i) => new { Char = c, Index = i })
.ToDictionary(c => c.Char, c => c.Index);
///
/// Convert a long to a Base36 string
///
/// The number to convert
/// A string representing the number in Base36
public static string ToString(long value)
{
long targetBase = BaseChars.Length;
// Determine exact number of characters to use.
char[] buffer = new char[Math.Max(
(int)Math.Ceiling(Math.Log(value + 1, targetBase)), 1)];
var i = buffer.Length;
do
{
buffer[--i] = BaseChars[value % targetBase];
value = value / targetBase;
}
while (value > 0);
return new string(buffer, i, buffer.Length - i);
}
///
/// Converts a Base64 string back into a number
///
/// The string to convert
/// The number resulting from converting the string
public static long FromString(string number)
{
char[] chrs = number.ToLower().ToCharArray();
int m = chrs.Length - 1;
int n = BaseChars.Length, x;
long result = 0;
for (int i = 0; i < chrs.Length; i++)
{
x = CharValues[chrs[i]];
result += x * (long)Math.Pow(n, m--);
}
return result;
}
}