Converting Javascript Code to Delphi
I am trying to convert javascript code to delphi but I failed ...
this is the javascript code:
/* generate random progress-id */
var uuid = "";
var i;
for (i = 0; i < 32; i++) {
uuid += Math.floor(Math.random() * 16).toString(16);
}
and this is my attempt at delphi:
function uid :string ;
var
i :integer;
begin
for I := 0 to 31 do begin
result := result + inttostr(floor(random * 16));
end;
end;
and this is the result for java script code
a638aa8f74e2654c725fd3cdcf2927d3
my knowledge in delphi is limited so I don't know what to do next.
I would like to get some help and inquire from her.
+3
source to share
1 answer
Literally, this is what the function looks like 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 lowercase "id" use the AnsiLowerCase function .
EDIT
In the name of correctness, the homebrew method from above is not recommended - it's just a literal translation of the javascript snippet. This can 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 lowercase "id" notice above is also here.
+7
source to share