Print a GUID variable

Viewed 69431

I have a GUID variable and I want to write inside a text file its value. GUID definition is:

typedef struct _GUID {          // size is 16
    DWORD Data1;
    WORD   Data2;
    WORD   Data3;
    BYTE  Data4[8];
} GUID;

But I want to write its value like:

CA04046D-0000-0000-0000-504944564944

I observed that:

  • Data1 holds the decimal value for CA04046D
  • Data2 holds the decimal value for 0
  • Data3 holds the decimal value for next 0

But what about the others?

I have to interpret myself this values in order to get that output or is there a more direct method to print such a variable?

11 Answers

You can eliminate the need for special string allocations/deallocations by using StringFromGUID2()

GUID guid = <some-guid>;
// note that OLECHAR is a typedef'd wchar_t
wchar_t szGUID[64] = {0};
StringFromGUID2(&guid, szGUID, 64);
std::string
GuidToString(const GUID& guid, bool lower = false)
{
    const char* hexChars = lower ? "0123456789abcdef" : "0123456789ABCDEF";

    auto f = [hexChars](char* p, unsigned char v)
    {
        p[0] = hexChars[v >> 4];
        p[1] = hexChars[v & 0xf];
    };

    char s[36];
    f(s, static_cast<unsigned char>(guid.Data1 >> 24));
    f(s + 2, static_cast<unsigned char>(guid.Data1 >> 16));
    f(s + 4, static_cast<unsigned char>(guid.Data1 >> 8));
    f(s + 6, static_cast<unsigned char>(guid.Data1));
    s[8] = '-';
    f(s + 9, static_cast<unsigned char>(guid.Data2 >> 8));
    f(s + 11, static_cast<unsigned char>(guid.Data2));
    s[13] = '-';
    f(s + 14, static_cast<unsigned char>(guid.Data3 >> 8));
    f(s + 16, static_cast<unsigned char>(guid.Data3));
    s[18] = '-';
    f(s + 19, guid.Data4[0]);
    f(s + 21, guid.Data4[1]);
    s[23] = '-';
    f(s + 24, guid.Data4[2]);
    f(s + 26, guid.Data4[3]);
    f(s + 28, guid.Data4[4]);
    f(s + 30, guid.Data4[5]);
    f(s + 32, guid.Data4[6]);
    f(s + 34, guid.Data4[7]);

    return std::string(s, 36);
}
Related