Android Code Snippet [B4X] UUID version 4 Generator

Extracted from this Thread:
https://www.b4x.com/android/forum/threads/guid-vs-uuid-can-i-use-guid-as-uuid.110970/#post-692302

B4X:
Sub UUIDv4 As String
   Dim sb As StringBuilder
   sb.Initialize
   For Each stp As Int In Array(8, 4, 4, 4, 12)
       If sb.Length > 0 Then sb.Append("-")
       For n = 1 To stp
           Dim c As Int = Rnd(0, 16)
           If c < 10 Then c = c + 48 Else c = c + 55
           If sb.Length = 19 Then c = Asc("8")
           If sb.Length = 14 Then c = Asc("4")
           sb.Append(Chr(c))
       Next
   Next
   Return sb.ToString.ToLowerCase
End Sub
 

Lucas Siqueira

Active Member
Licensed User
Longtime User
The previous code fixed the character 8 in the first position of the fourth group of characters. Now it can be 8, 9, a, or b

B4X:
Sub UUIDv4 As String
    ' Initializes a StringBuilder to construct the UUID string
    Dim sb As StringBuilder
    sb.Initialize

    ' Defines the format of the UUID with 5 groups (8, 4, 4, 4, 12 characters respectively)
    For Each stp As Int In Array(8, 4, 4, 4, 12)
        ' Adds a hyphen (-) between groups, except before the first group
        If sb.Length > 0 Then sb.Append("-")

        ' Iterates through the number of characters in each group
        For n = 1 To stp
            ' Generates a random number between 0 and 15 (hexadecimal)
            Dim c As Int = Rnd(0, 16)

            ' Converts the random number into a hexadecimal character (0-9 or a-f)
            If c < 10 Then
                c = c + 48 ' Converts numbers 0-9 to their ASCII values (48 = '0')
            Else
                c = c + 87 ' Converts numbers 10-15 to their ASCII values ('a'-'f', 87 is the offset)
            End If

            ' If we're at the start of the fourth group (sb.Length = 19), adjusts the first character
            ' This value must be 8, 9, a, or b, as defined by the UUID v4 specification
            If sb.Length = 19 Then
                ' Creates an array containing the possible values for the first character of the fourth group
                Dim variantArray() As String = Array As String("8", "9", "a", "b")
                ' Randomly selects one value from the array and converts it to ASCII
                c = Asc(variantArray(Rnd(0, variantArray.Length)))
            End If

            ' If we're at the start of the third group (sb.Length = 14), defines the UUID version as 4
            ' This is required by the UUID v4 specification
            If sb.Length = 14 Then
                c = Asc("4") ' Sets the character to "4", indicating version 4
            End If

            ' Appends the generated character to the StringBuilder
            sb.Append(Chr(c))
        Next
    Next

    ' Returns the complete UUID string, converted to lowercase
    Return sb.ToString.ToLowerCase
End Sub
 
Top