Search code examples
c++guiduuid

How to convert a UUID that saved in an array of bytes into a string (c++)


I have a UUID that saved as a 16 byte data like this:

   unsigned char uuid[16]; //128-bits unique identifier

and I want to convert it to a std::string. I can probably write a loop to go thought all bytes and generate the string, but I am looking for a simpler/faster solution. Is there any such solution?


Solution

  • If you really want to avoid a loop, you can always do something like:

    char str[37] = {};
    sprintf(str, 
    "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", 
        uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7],
        uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]
    );
    

    Not really elegant, but i think it's the best you can get without loop and without platform dependency.