How to generate a UUID (Universally Unique Identifier) in Pascal

1 Answer

0 votes
program UUIDv4Generator;

{$mode objfpc}{$H+}{$J-}

{
  Generate a UUID v4 (random-based) in idiomatic Free Pascal.

  UUID v4 rules (RFC 4122):
  - 16 bytes total
  - Version (byte 6): high nibble must be 0100 (version 4)
  - Variant (byte 8): high bits must be 10xx (RFC 4122 variant)
}

uses
  SysUtils;

type
  TUUIDBytes = array[0..15] of Byte;

function GenerateRandomBytes: TUUIDBytes;
var
  i: Integer;
begin
  for i := 0 to 15 do
    Result[i] := Random(256);
end;

procedure ApplyUUIDv4Rules(var B: TUUIDBytes);
begin
  B[6] := (B[6] and $0F) or $40;  // version 4
  B[8] := (B[8] and $3F) or $80;  // variant RFC 4122
end;

function UUIDBytesToString(const B: TUUIDBytes): string;
begin
  Result :=
    Format('%.2x%.2x%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x',
      [B[0], B[1], B[2], B[3],
       B[4], B[5],
       B[6], B[7],
       B[8], B[9],
       B[10], B[11], B[12], B[13], B[14], B[15]]);
end;

function GenerateUUIDv4: string;
var
  Bytes: TUUIDBytes;
begin
  Bytes := GenerateRandomBytes;
  ApplyUUIDv4Rules(Bytes);
  Result := LowerCase(UUIDBytesToString(Bytes));  // ensure lowercase output
end;

begin
  Randomize;
  WriteLn('Generated UUID v4: ', GenerateUUIDv4);
end.



(*
run:    

Generated UUID v4: fade54f7-02ad-4020-abf1-b02f0711e63c

*)

 



answered Jul 14 by avibootz
...