Skip to content

Instantly share code, notes, and snippets.

@vincenthsu
Last active April 3, 2023 20:00
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vincenthsu/8fab51834e3a04074a57 to your computer and use it in GitHub Desktop.
Save vincenthsu/8fab51834e3a04074a57 to your computer and use it in GitHub Desktop.
GUID to std::string, std::string to GUID
#ifndef _WIN32
typedef struct _GUID {
uint32_t Data1;
uint16_t Data2;
uint16_t Data3;
uint8_t Data4[8];
} GUID;
#endif
GUID StringToGuid(const std::string& str)
{
GUID guid;
sscanf(str.c_str(),
"{%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx}",
&guid.Data1, &guid.Data2, &guid.Data3,
&guid.Data4[0], &guid.Data4[1], &guid.Data4[2], &guid.Data4[3],
&guid.Data4[4], &guid.Data4[5], &guid.Data4[6], &guid.Data4[7] );
return guid;
}
std::string GuidToString(GUID guid)
{
char guid_cstr[39];
snprintf(guid_cstr, sizeof(guid_cstr),
"{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
guid.Data1, guid.Data2, guid.Data3,
guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
return std::string(guid_cstr);
}
@Environmentc2
Copy link

Run-time Check Failure #2 - Stack around the "guid" was corrupted;
the code are as follow:
GUID YourCarAPI::StringToGuid(const std::string& str)
{

GUID guid;
sscanf(str.c_str(),

	"{%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx}",

	&guid.Data1, &guid.Data2, &guid.Data3,

	&guid.Data4[0], &guid.Data4[1], &guid.Data4[2], &guid.Data4[3],

	&guid.Data4[4], &guid.Data4[5], &guid.Data4[6], &guid.Data4[7] );

return guid;

}

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