Convert a string into BASE62

僤鯓⒐⒋嵵緔 提交于 2019-12-21 05:18:07

问题


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.


回答1:


Try the C# library available here which adds some extension methods to allow you to convert a byte array to and from BASE62.

  • https://github.com/renmengye/base62-csharp

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();



回答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;
}



回答3:


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/



来源:https://stackoverflow.com/questions/17745025/convert-a-string-into-base62

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!