How do I parse a decimal UUID string in C?

1.2k views Asked by At

I've got a UUID (128-bit number) represented as a decimal number and I need to parse it into numeric form in C. My target data structure is a char[16] and using a bignum library is not an option. Can someone point me to a suitable algorithm?

1

There are 1 answers

0
aaz On

The naïve algorithm is quite simple:

char number[] = "79625568443717255337188391839044322587";
unsigned char uuid[16] = { 0 };

for (char* n = number; *n; n++) {
    unsigned c = *n - '0';
    for (int i = 0; i < 16; i++) {
        c += uuid[i] * 10;
        uuid[i] = c % 256;
        c /= 256;
    }
}

This is simpler than a typical bignum operation because the multiplier 10 is smaller than the unit size and the number length is fixed.

You could speed it up by working in larger units than char (e.g. uint32_t), as long as c is larger still (e.g. uint64_t), though I doubt it's necessary.