Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Base36 conversion

Title: Base36 conversion Question: I need to convert a series of DWords into a hashed string that can be used as a serial number. Answer: I had to write a license control for an application and needed to present a hashed string for the user that could be read over phone to a call-center support in able to pass importent license data from the application. One way to do this is was to create a 20 byte long hardware profile that included CPU information - 2 bytes, MacID - 5 bytes, CRC32 checksum of windows username and company name - 8 bytes and the harddrive serial number. All this information was then needed to be passed to the support and checked for a valid license. One way to pass these 20 bytes was to convert them into five base36 values containing [A..Z] and [0..9] characters as represantation. The resulting string would look something as: "DFD3LQ-FSDE3Y-WXHU89-34KLAS-WELPWE" Below you can find functions to convert numbers into base36 strings and back again. ------------ function NumToBase36(Value : DWord) : string; const BaseType = 36; Base36Table = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; Var BaseIdx : Word; begin result := ''; repeat BaseIdx := Value mod BaseType; Value := Value div BaseType; result := Base36Table[BaseIdx+1] + result; until value = 0; end; function Base36ToNum(Base36 : string) : Dword; const BaseType = 36; Base36Table = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; Var lp0,BaseIdx,Mult : integer; begin result := 0; Mult := 1; for lp0 := Length(Base36) downto 1 do begin BaseIdx := pos(Upcase(Base36[lp0]),Base36Table)-1; if BaseIdx inc(result,(BaseIdx*Mult)); Mult := Mult * BaseType; end; end;