Code for cross-platform GUID/UUID?

Just starting out? Need help? Post your questions and find answers here.
Mistrel
Addict
Addict
Posts: 3415
Joined: Sat Jun 30, 2007 8:04 pm

Code for cross-platform GUID/UUID?

Post 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?
User avatar
netmaestro
PureBasic Bullfrog
PureBasic Bullfrog
Posts: 8451
Joined: Wed Jul 06, 2005 5:42 am
Location: Fort Nelson, BC, Canada

Post 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.
BERESHEIT
Mistrel
Addict
Addict
Posts: 3415
Joined: Sat Jun 30, 2007 8:04 pm

Post 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
Straker
Enthusiast
Enthusiast
Posts: 701
Joined: Wed Apr 13, 2005 10:45 pm
Location: Idaho, USA

Post by Straker »

Sweet. Thanks!
Image Image
Post Reply