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?
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.
Answer on this question is wrong by all means.
According to https://en.wikipedia.org/wiki/Universally_unique_identifier#Format
This is the correct code:
char str[37] = {};
unsigned long data1 = *reinterpret_cast<unsigned long*>(uuid);
unsigned short data2 = *reinterpret_cast<unsigned short*>(uuid + 4);
unsigned short data3 = *reinterpret_cast<unsigned short*>(uuid + 6);
sprintf(str,
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
data1, data2, data3,
uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]
);
Write a loop. For each byte, snprintf of %#02x. Do not forget the conventional dashes.
There is no platform-independent (ie POSIX) API that formats UUIDs, so this is the best you are going to get.
basic_string supplys this constructor:
basic_string(const E *s, size_type n, const A& al = A());
So you can do it like this:
string strUuid(uuid, 16);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.