Skip to content

Instantly share code, notes, and snippets.

@Quacky2200
Last active September 3, 2021 19:45
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 Quacky2200/f8924624e1fd8669cf992a787e0a2b91 to your computer and use it in GitHub Desktop.
Save Quacky2200/f8924624e1fd8669cf992a787e0a2b91 to your computer and use it in GitHub Desktop.
C# Edition of Base62 integer encode/decode originally from https://gist.github.com/sebastien-p/1170594
using System;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
class Program
{
public static string Base62EncodeInt(int Original)
{
string Result = "";
for (decimal Temp = Original; Temp > 0; Temp = Math.Floor((Temp / 62)))
{
// Base62 Encode source https://gist.github.com/sebastien-p/1168420/bc98b64ef1e6f18ee4379ad57df1a65d205b634f
// a%62 -> 0-61
// 0-9 | 36-61 | 10-35
// 48-57 | 65-90 | 97-121
// 0-9 | A-Z | a-z
var Modulus = Temp % 62;
Result = ((char)((
Modulus > 9 ?
(Modulus > 35 ? 29 : 87) :
48
) + Modulus)) + Result;
}
return Result;
}
public static int Base62DecodeInt(string Encoded)
{
// Base62 decode source https://gist.github.com/sebastien-p/1170594 - base62 decode
int Result = 0;
int[] ASCIIPad = { 0, 48, 29, 87 };
foreach (var Char in Encoded)
{
Result = Result * 62 + Char - ASCIIPad[Char >> 5];
}
return Result;
}
public static string Base62EncodeLong(ulong Original)
{
string Result = "";
for (decimal Temp = Original; Temp > 0; Temp = Math.Floor((Temp / 62)))
{
// https://gist.github.com/sebastien-p/1168420/bc98b64ef1e6f18ee4379ad57df1a65d205b634f - base62 encode
// a%62 -> 0-61
// 0-9 | 36-61 | 10-35
// 48-57 | 65-90 | 97-121
// 0-9 | A-Z | a-z
var Modulus = Temp % 62;
Result = ((char)((
Modulus > 9 ?
(Modulus > 35 ? 29 : 87) :
48
) + Modulus)) + Result;
}
return Result;
}
public static ulong Base62DecodeLong(string Encoded)
{
// https://gist.github.com/sebastien-p/1170594 - base62 decode
ulong Result = 0;
int[] ASCIIPad = { 0, 48, 29, 87 };
foreach (var Char in Encoded)
{
Result = Result * 62ul + Char - (ulong)ASCIIPad[Char >> 5];
}
return Result;
}
static void Main(string[] args)
{
string intA = "BD45A", intB, ulongA = "140bytes", ulongB;
int intValue;
ulong ulongValue;
Console.WriteLine("string: " + intA);
Console.WriteLine("decoded: " + (intValue = Base62DecodeInt(intA)));
Console.WriteLine("encoded: " + (intB = Base62EncodeInt(intValue)));
Console.WriteLine("match: " + (intB == intA ? "Yes" : "No"));
Console.WriteLine("");
Console.WriteLine("string: " + ulongA);
Console.WriteLine("decoded: " + (ulongValue = Base62DecodeLong(ulongA)));
Console.WriteLine("encoded: " + (ulongB = Base62EncodeLong(ulongValue)));
Console.WriteLine("match: " + (ulongB == ulongA ? "Yes" : "No"));
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment