Skip to content

Instantly share code, notes, and snippets.

@Aaronontheweb
Last active May 29, 2021 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aaronontheweb/449d565754d5f9bce475653842317277 to your computer and use it in GitHub Desktop.
Save Aaronontheweb/449d565754d5f9bce475653842317277 to your computer and use it in GitHub Desktop.
Base64 Encoding with Span<T>
void Main()
{
/*
Input: [0], Output: [A] (length=1)
Input: [1], Output: [B] (length=1)
Input: [18446744073709551615], Output: [~~~~~~~~~~P] (length=11)
Input: [0], Output: [A] (length=1)
Input: [34343], Output: [nYI] (length=3)
*/
var values = new long[] { 0L, 1L, long.MaxValue, 34343};
foreach (var val in values) {
var encoded = Base64Encode(val);
Console.WriteLine("Input: [{0}], Output: [{1}] (length={2})", val, encoded, encoded.Length);
}
}
const string Base64Chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+~";
/*
* Can't accept negative values (will throw an IndexOutOfRange) but due to compatability
* constraints, can't change this function to accept ulong
*/
string Base64Encode(long value, string prefix = "$")
{
Span<char> sb = stackalloc char[11 + prefix?.Length ?? 0];
var spanIndex = 0;
if (!string.IsNullOrEmpty(prefix) && prefix.Length > 0) {
prefix.AsSpan().CopyTo(sb);
spanIndex = prefix.Length;
}
var next = value;
do
{
var index = (int)(next & 63);
sb[spanIndex++] = Base64Chars[index];
next = next >> 6;
} while (next != 0);
return sb.Slice(0, spanIndex).ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment