Does anyone have a nice code snippet for a Guid to Base34 encoder/decoder, I've googled around for it previously and never really found any good sources.
A:
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));
Darin Dimitrov
2010-01-06 14:29:03
That's Base32, still not Base34.
MSalters
2010-01-06 14:46:04
@MSalters How would that become Base32 from Base64?
Chris Marisic
2010-01-06 15:14:40
+1
A:
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)
David
2010-01-07 15:21:40
A project like this was exactly what I was looking for. Atleast it's 8 characters less than a Guid to have a customer read back to an agent over the phone!
Chris Marisic
2010-01-07 16:21:21
Although I did notice if you replace longs with decimals in his code to support higher order values it seems to introduce some type of floating point math issue that causes the least significant bits to be incorrect that if you an encode a number then decode it you get a different value back. Of course it's trivial to split the Guid into sets of 4 characters. Although that makes me wonder if there would ever be a time that a 4 digit hex number converted to base34 would ever be any value other than 3 digit base34 number.
Chris Marisic
2010-01-07 16:37:31
A:
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)