AP.NET/Utils/Base36.cs

44 lines
1.3 KiB
C#
Raw Normal View History

namespace ActivityPub.Utils;
// https://stackoverflow.com/a/35004409
public class Base36
{
private static readonly char[] BaseChars =
"0123456789abcdefghijklmnopqrstuvwxyz".ToCharArray();
private static readonly Dictionary<char, int> CharValues = BaseChars
.Select((c, i) => new { Char = c, Index = i })
.ToDictionary(c => c.Char, c => c.Index);
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);
}
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;
}
}