6

I'm looking for the c# code to convert a string into BASE62, like this:

http://www.molengo.com/base62/title/base62-encoder-decoder

I need those encode and decode-methods for URL-Encoding.

Pierre Arnaud
  • 10,212
  • 11
  • 77
  • 108
fubo
  • 44,811
  • 17
  • 103
  • 137

3 Answers3

5

Background on BINARY to TEXT Encoding schemes:

https://en.wikipedia.org/wiki/Base62

https://en.wikipedia.org/wiki/Base64

Good explanation of the BASE62 encoding scheme:

https://www.codeproject.com/Articles/1076295/Base-Encode

Try the C# libraries available here which adds some extension methods to allow you to convert a byte array to and from BASE62 (binary-to-text encoding schemes).

Plenty of base62 libraries on github, have a look:

If your source data is contained in a "string" then you would first need to convert your "string" to a suitable byte array.

But be careful, to use the correct string to byte conversion call....as you may want the bytes to be the ASCII characters, or the Unicode byte stream etc i.e. Encoding.GetBytes(text) or System.Text.ASCIIEncoding.ASCII.GetBytes(text);, etc

byte[] bytestoencode = ..... 

string encodedasBASE62 = bytestoencode.ToBase62();

.....

byte[] bytesdecoded = encodedasBASE62.FromBase62();
Colin Smith
  • 12,375
  • 4
  • 39
  • 47
  • This library does not work. For `{ 255 }` it gives the result `"z7"` instead of `"47"`. Also, leading zeroes matter where they shouldn't, so `{ 0, 255 }` gives another result, which is `"0FF"`. – Maxime Recuerda Nov 07 '21 at 17:46
2

You can do this for any base, this way:

static string ToBase62(ulong number)
{
var alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var n = number;
ulong basis = 62;
var ret = "";
while (n > 0)
 {
   ulong temp = n % basis;
   ret = alphabet[(int)temp] + ret;
   n = (n / basis);

 }
 return ret;
}
true_gler
  • 544
  • 6
  • 23
  • 3
    This is for converting a ulong to base62, not a string (which is asked in the question). – Scott Lyons Feb 19 '19 at 14:35
  • 1
    This is incorrect , the string should be "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" and not "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" – confusednerd Dec 28 '20 at 01:48
1

not the real answer but hopefully this helps you to build a C# Version of it:

Javascript Base62 Encode/Decode:

http://x443.wordpress.com/2012/03/18/javascript-base62-encode-decode/

Meister Schnitzel
  • 304
  • 2
  • 4
  • 11