开发者

Guid to Base34 encoder/decoder

Does anyone have a nice code snippet for a Guid to Base34 encoder/decoder, I've开发者_如何学C googled around for it previously and never really found any good sources.


This Number base conversion class in C# could be fairly easily extended to do base34 (or others if you think people will confuse S and 5 or b and 6 or i and j or B and 8 or 9 and g or whatever)


Here's a simplified version... It basically takes a string, calculates the MD5 hash, extracts the first four bytes as an unsigned long (effective mapping the string to a 4-byte number), converts that to base36 and then swaps out the "oh" and "zero" chars for "X" and "Y". Then, it ensures the final string is only six chars, padding with "Z" chars if needed.

require 'digest/md5'

# create an easy-to-read 6-digit unique idno
idno = original # starting string
idno = Digest::MD5.digest(idno).unpack("N").first # digest as unsigned long
idno = idno.to_s(36).upcase.tr("0O","XY") # convert to base34 (no "oh" or "zero")
idno = idno[0,6].ljust(6,"Z") # final 6-digit unique idno (pad with "Z" chars)


The key methods here are ToByteArray and this particular constructor.

Encode:

string encodedGuid = Convert.ToBase64String(guid.ToByteArray());

Decode:

Guid guid = new Guid(Convert.FromBase64String(encodedGuid));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜