Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string into BASE62

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.

like image 731
fubo Avatar asked Jul 19 '13 11:07

fubo


People also ask

How do I use base62?

The base62 encoding scheme uses 62 characters. The characters consist of the capital letters A-Z, the lower case letters a-z and the numbers 0–9. It is a binary-to-text encoding schemes that represent binary data in an ASCII string format.

What is base 62 conversion?

What is Base-62? (Definition) The base62 is an encoding method with 62 characters (ie all alphanumeric characters: digits 0-9, upper case letters A-Z and lower case a-z) allowing the encoding of binary strings.

Is base62 URL safe?

The main advantage of base62 is that it is URL-safe (as opposed to base64 ) due to the lack of special characters such as ' / ' or ' = '.


2 Answers

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:

  • https://github.com/JoyMoe/Base62.Net
  • https://github.com/ghost1face/base62
  • https://github.com/rossdempster/base62csharp
  • https://github.com/renmengye/base62-csharp (claims below that it doesn't work...raise any issues with them)

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();
like image 166
CSmith Avatar answered Oct 29 '22 14:10

CSmith


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;
}
like image 2
true_gler Avatar answered Oct 29 '22 14:10

true_gler