Skip to content

Instantly share code, notes, and snippets.

@ststeiger
Last active August 20, 2024 14:08
Show Gist options
  • Save ststeiger/717aeb098e0469b85837755fa5e88e55 to your computer and use it in GitHub Desktop.
Save ststeiger/717aeb098e0469b85837755fa5e88e55 to your computer and use it in GitHub Desktop.
How to generate GUID/uuid-V4 in different programming languages
// .NET
System.Guid.NewGuid().ToString()
// JS:
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);  
return v.toString(16);
});
}
console.log(generateUUID());
// Python:
import uuid
def generate_guid():
return str(uuid.uuid4())
if __name__ == "__main__":
guid = generate_guid()
print(guid)
// Java:
import java.util.UUID;
public class GUIDExample {
public static void main(String[] args) {
UUID uuid = UUID.randomUUID();
System.out.println(uuid);
String uuidString = uuid.toString();
System.out.println(uuidString);
}
}
// PHP:
function generate_uuid() {
$data = random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Set version to 4
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // Set variant to 1
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
echo generate_uuid();
// Ruby:
require 'securerandom'
uuid = SecureRandom.uuid
puts uuid
// GO:
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
u, err := uuid.NewRandom()
if err != nil {
fmt.Println(err)
}
fmt.Printf("UUID: %s\n", u)
}
// Swift:
import Foundation
let uuid = UUID()
print(uuid.uuidString)
// R:
install.packages("uuid")
library(uuid)
uuid::UUIDgenerate()
// Delphi/Pascal:
uses
SysUtils,
Math; // For random number generation
function GenerateUUID(var UUID: string): Boolean;
const
UUID_LENGTH = 36;
HEX_CHARS = '0123456789abcdef';
var
RandomBytes: array[0..15] of Byte;
I, J: Integer;
CharIndex: Integer;
begin
// Generate 16 random bytes
for I := 0 to 15 do
RandomBytes[I] := Byte(Random(256));
// Set version to 4 (bits 6 and 7 of byte 6)
RandomBytes[6] := (RandomBytes[6] and $0F) or $40;
// Set variant to 1 (bit 8 of byte 8)
RandomBytes[8] := (RandomBytes[8] and $3F) or $80;
// Format the UUID string
J := 0;
for I := 0 to 15 do
begin
CharIndex := Ord(RandomBytes[I]) shr 4;
UUID[J] := HEX_CHARS[CharIndex + 1];
Inc(J);
CharIndex := Ord(RandomBytes[I]) and $0F;
UUID[J] := HEX_CHARS[CharIndex + 1];
Inc(J);
if (I = 3) or (I = 5) or (I = 7) or (I = 9) then
UUID[J] := '-';
Inc(J);
end;
UUID[UUID_LENGTH] := #0; // Null-terminate the string
Result := True;
end;
// C:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void generate_uuid(char *uuid_str) {
unsigned char data[16];
// Seed the random number generator
srand(time(NULL));
// Generate random data
for (int i = 0; i < 16; i++) {
data[i] = rand() % 256;
}
// Set version to 4
data[6] &= 0x0f;
data[6] |= 0x40;
// Set variant to 1
data[8] &= 0x3f;
data[8] |= 0x80;
// Format the UUID string
sprintf(uuid_str, "%02x%02x-%02x%02-%02x%02-%02x%02-%02x%02%02%02%02%02%02",
data[0], data[1], data[2], data[3],
data[4], data[5], data[6], data[7],
data[8], data[9], data[10], data[11],
data[12], data[13], data[14], data[15]);
}
int  
main() {
char uuid[37];
generate_uuid(uuid);
printf("UUID: %s\n", uuid);
return 0;
}
// Ada:
with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Generate_UUID (UUID : out String) is
type Byte is mod 2**8;
Random_Bytes : array (0 .. 15) of Byte;
Hex_Digits : constant String := "0123456789abcdef";
I, J : Integer;
Char : Character;
begin
-- Generate 16 random bytes (replace with a cryptographically secure RNG)
for I in Random_Bytes'Range loop
Random_Bytes(I) := Byte(Random(2**8));
end loop;
-- Set version to 4 (bits 6 and 7 of byte 6)
Random_Bytes(6) := (Random_Bytes(6) and 15) or 64;
-- Set variant to 1 (bit 8 of byte 8)
RandomBytes(8) := (RandomBytes(8) and 63) or 128;
-- Format the UUID string
J := 0;
for I in Random_Bytes'Range loop
Char := Hex_Digits((Random_Bytes(I) / 16) + 1);
UUID(J) := Char;
J := J + 1;
Char := Hex_Digits((Random_Bytes(I) mod 16) + 1);
UUID(J) := Char;
J := J + 1;
if I in (3, 5, 7, 9) then
UUID(J) := '-';
J := J + 1;
end if;
end loop;
UUID(J) := Nul;
end Generate_UUID;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment