Skip to content

Instantly share code, notes, and snippets.

@streadway
Created September 12, 2012 21:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save streadway/3710066 to your computer and use it in GitHub Desktop.
Save streadway/3710066 to your computer and use it in GitHub Desktop.
Example UUID in 22 bytes. Linux: `cc -luuid uuid22.c` Darwin: `cc uuid22.c`
#include <stdio.h>
#include <uuid/uuid.h>
#include <sys/types.h>
u_int64_t bits2uint64(unsigned char const bits[]) {
return ((u_int64_t)bits[0] << 56)
| ((u_int64_t)bits[1] << 48)
| ((u_int64_t)bits[2] << 40)
| ((u_int64_t)bits[3] << 32)
| ((u_int64_t)bits[4] << 24)
| ((u_int64_t)bits[5] << 16)
| ((u_int64_t)bits[6] << 8)
| (u_int64_t)bits[7];
}
void uuid_init(uuid_t u) {
// cross platform ifdef here
uuid_generate(u);
}
// least 22 bytes allocated and owned at call-site
void uuid_fmt22(uuid_t u, char buf[]) {
static const int len = 11;
static const int base = 58;
static const char digits[] =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHJKLMNOPQRSTUVWXYZ"
"2345679"; // Excludes I180
int i,j;
// for hi/lo of 128 bits
for (i=0; i < 2; i++) {
u_int64_t block = bits2uint64(u+(i*8));
for (j=0; j < len; j++) {
buf[j+(i*len)] = digits[block % base];
block = block / base;
}
}
}
int main(int argc, char** argv) {
uuid_t u;
char str[23];
char fmt[37];
int i;
for (i = 0; i < 10; i++) {
uuid_init(u);
uuid_unparse_lower(u, fmt);
uuid_fmt22(u, str);
str[22] = '\0';
printf("uuid: %s '%s'\n", fmt, str);
}
return 0;
}
@pilkch
Copy link

pilkch commented Nov 23, 2016

Can you please explain this comment? I can see they are missing from the digits array, but I'm not sure why.
// Excludes I180

Edit:
Ahh, I think I worked it out, it is encoding with Base58, so we have 62 characters in a-zA-Z0-9 and remove 4 of them to get our Base58 characters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment