Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Fast ID generation

Title: Fast ID generation Question: How to generate random ID Answer: Sometimes I have to send registration codes for my applications thru fax or postoffice. In that case it is essential to prevent misundestanding of any characted in code. I use following code for generation passwords with well distinguishable characters (furthermore it works very fast ;) ) function RandomStr (ALen : integer) : string; // ALen - desired length of password const Tbl : array [0 .. $1F] of char = ( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); var i, n, k, x, j : integer; begin SetString (Result, nil, ALen); n := ALen * 5; // bits in random number j := 1; while n 0 do begin if n 30 then k := 30 // work with 32-bits numbers else k := n; x := Random (1 shl k - 1); for i := 1 to k div 5 do begin Result [j] := Tbl [x and $1F]; inc (j); x := x ShR 5; end; dec (n, k) end; end; { of function RandomStr --------------------------------------------------------------}