javascriptdelphirandomuid

Converting JavaScript (random UID) code to Delphi


I'm trying to convert JavaScript code to Delphi but I failed. Javascript:

/* generate random progress-id */
var uuid = "";
var i;
for (i = 0; i < 32; i++) {
  uuid += Math.floor(Math.random() * 16).toString(16);
}

...and its output:

a638aa8f74e2654c725fd3cdcf2927d3

My try in Delphi:

function uid: String;
var
  i: Integer;
begin
  for I := 0 to 31 do begin
    result := result + IntToStr(Floor(Random * 16));
  end;
end;

My knowledge in Delphi is limited, so I don't know what to do more. I would like to see some help and learn from it.


Solution

  • Literally, here is how the function looks in delphi:

    function uid: String;
    var
      i: Integer;
    begin
      for i := 0 to 31 do
        Result := Result + IntToHex(Random(16), 1);
    end;
    

    If you need a lowercased "id" - use the AnsiLowerCase function.

    EDIT

    In the name of correctness, the homebrew method from above is not recommended- it's just a literally translation of the javascript snippet. It could lead to collisions (and will).

    The following function is recommended:

    function uid: String;
    var
      myGuid: TGUID;
    begin
      if Succeeded(CreateGUID(myGUID)) then
        Result := Format('%0.8X%0.4X%0.4X%0.2X%0.2X%0.2X%0.2X%0.2X%0.2X%0.2X%0.2X',
          [myGUID.D1, myGUID.D2, myGUID.D3,
          myGUID.D4[0], myGUID.D4[1], myGUID.D4[2], myGUID.D4[3],
          myGUID.D4[4], myGUID.D4[5], myGUID.D4[6], myGUID.D4[7]]) else
        {TODO: some error processing - something bad happened}
    end;
    

    The notice for the lowercased "id" from above is valid here too.