Page 1 of 1

Code for cross-platform GUID/UUID?

Posted: Wed Jul 01, 2009 3:01 am
by Mistrel
I'm currently using CoCreateGuid_ and StringFromGUID2_ to come up with a fairly unique number but this is not cross-platform. Does anyone know how these codes are generated?

Posted: Wed Jul 01, 2009 3:41 am
by netmaestro
I guess this would make a random string in GUID format. Not sure if it's what you're after or not.

Code: Select all

Dim bytes$(16)

For i=1 To 16
  bytes$(i)=RSet(Hex(Random(255)),2,"0")
Next

guid$ = "{"
For i=1 To 4
  guid$+bytes$(i)
Next
guid$+"-"
For i=5 To 6
  guid$+bytes$(i)
Next
guid$+"-"
For i=7 To 8
  guid$+bytes$(i)
Next
guid$+"-"
For i=9 To 10
  guid$+bytes$(i)
Next
guid$+"-"
For i=11 To 16
  guid$+bytes$(i)
Next

guid$+"}"

Debug guid$
Your likelihood of generating two of these alike is very small but if you need to be certain you could maintain a database of all previously-generated GUIDs and check it each time you make one.

Posted: Wed Jul 01, 2009 4:41 am
by Mistrel
According to Wikipedia this conforms to version 4 (random) OSF UUID standard:

Code: Select all

Structure UUID
  Byte.b[16]
EndStructure

Define UUID.UUID

For i=0 To 16-1
  UUID\Byte[i]=Random(255)
Next
UUID\Byte[9]=128+Random(63)
UUID\Byte[7]=64+Random(15)

For i=0 To 16-1
  If i=3 Or i=5 Or i=7
    GUID.s+"-"
  EndIf
  GUID.s+RSet(Hex(UUID\Byte[i]&$FF),2,"0")
Next

Debug GUID.s

Posted: Thu Jul 02, 2009 9:06 pm
by Straker
Sweet. Thanks!