siliconid/siliconid.c

57 lines
1.5 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
#define BASE62 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
// Convert a number to Base-62
void to_base62(uint64_t num, char *output, int length) {
char buffer[16] = {0}; // Temporary storage
int i = 0;
while (num > 0 && i < sizeof(buffer) - 1) {
buffer[i++] = BASE62[num % 62];
num /= 62;
}
// Reverse the string to get the correct order
int j = 0;
while (i > 0) {
output[j++] = buffer[--i];
}
// Ensure fixed length (pad with '0' if needed)
while (j < length) {
output[j++] = '0';
}
output[j] = '\0'; // Null-terminate the string
}
// Generate the UID
void generate_uid(char *uid) {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
uint64_t epoch_2020 = 1577836800000ULL; // 2020-01-01 00:00:00 UTC in milliseconds
uint64_t now = (uint64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; // Current time in ms
uint64_t timestamp = (now - epoch_2020) % 1000000000000ULL; // Keep only 12 digits
uint64_t random_num = rand() % 100; // Random 2-digit number (00-99)
uint64_t final_num = timestamp * 100 + random_num;
// Convert to Base-62 and ensure 8-character output
to_base62(final_num, uid, 8);
}
int main() {
srand(time(NULL)); // Seed random number generator
char uid[9]; // 8 characters + null terminator
generate_uid(uid);
printf("Generated UID: %s\n", uid);
return 0;
}