From f134723e7e00b99df0f2d5a9656e86bd8ab82de4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 4 Dec 2021 13:09:00 -0600 Subject: add ToBase62String --- src/slskd/Common/Extensions.cs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 32a9b26e..d678541d 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -22,7 +22,9 @@ namespace slskd using System.IO; using System.Linq; using System.Net.Sockets; + using System.Numerics; using System.Reflection; + using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; @@ -284,6 +286,27 @@ namespace slskd return Path.Combine(path, sanitizedFilename).TrimStart('\\').TrimStart('/'); } + /// + /// Converts the byte array into a base 62 encoded string. + /// + /// The bytes to convert. + /// The converted bytes as a base 62 string. + public static string ToBase62String(this byte[] bytes) + { + const string alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + BigInteger dividend = new BigInteger(bytes); + var builder = new StringBuilder(); + + while (dividend != 0) + { + dividend = BigInteger.DivRem(dividend, alphabet.Length, out BigInteger remainder); + builder.Insert(0, alphabet[Math.Abs((int)remainder)]); + } + + return builder.ToString(); + } + /// /// Creates a copy of this instance with the specified parameters changed. /// -- cgit v1.2.3