-
Notifications
You must be signed in to change notification settings - Fork 1
/
GuidExtensions.cs
43 lines (32 loc) · 1.25 KB
/
GuidExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System.Text;
using System.Text.RegularExpressions;
// ReSharper disable CheckNamespace
namespace System;
public static class GuidExtensions
{
internal const string Alphabet = "BCDFGHJKLMNPQRSTVWXYZbcdfhjklmnpqrstvwxyz0123456789";
private static readonly Regex ValidShortGuid = new($"^[{Alphabet}]{{1,24}}$");
public static string ToShortString(this Guid inputGuid)
{
var guidBytes = inputGuid.ToByteArray();
var stringBuilder = new StringBuilder();
for (var guidSection = 0; guidSection < 2; guidSection++)
{
var section = new StringBuilder();
var startIndex = guidSection * 8;
var numericRepresentation = BitConverter.ToUInt64(guidBytes, startIndex);
while (numericRepresentation > 0)
{
var mod = (int)(numericRepresentation % (ulong)Alphabet.Length);
section.Append(Alphabet[mod]);
numericRepresentation /= (ulong)Alphabet.Length;
}
stringBuilder.Append(section.ToString().PadRight(12, 'B'));
}
return stringBuilder.ToString();
}
public static bool IsValidShortGuid(this string guidString)
{
return ValidShortGuid.IsMatch(guidString);
}
}