C++ 从无符号字符数组创建 GUID

标签 c++ arrays guid unsigned-char

我有一个函数,它将一个无符号字符数组(恰好 16 个值)作为输入,并通过将所有值解析为十六进制并将 guid 格式的字符串传递给 UuidFromStringA() 创建一个 GUID(来自 GUID 结构)

我的代码如下:

GUID CreateGuid(const uint8_t* data)
{
    createGuidFromBufferData(hexValues, data);
    int uuidCreationReturnCode = UuidFromStringA((RPC_CSTR)hexValues, &guid);
    return guid;
}
            
inline void createGuidFromBufferData(char* hexValues, const uint8_t* data)
{
    decimalToHexadecimal(data[3], hexValues, 0);
    decimalToHexadecimal(data[2], hexValues, 2);
    decimalToHexadecimal(data[1], hexValues, 4);
    decimalToHexadecimal(data[0], hexValues, 6);
    hexValues[8] = '-';
    decimalToHexadecimal(data[5], hexValues, 9);
    decimalToHexadecimal(data[4], hexValues, 11);
    hexValues[13] = '-';
    decimalToHexadecimal(data[6], hexValues, 14);
    decimalToHexadecimal(data[7], hexValues, 16);
    hexValues[18] = '-';
    decimalToHexadecimal(data[8], hexValues, 19);
    decimalToHexadecimal(data[9], hexValues, 21);
    hexValues[23] = '-';
    decimalToHexadecimal(data[10], hexValues, 24);
    decimalToHexadecimal(data[11], hexValues, 26);
    decimalToHexadecimal(data[12], hexValues, 28);
    decimalToHexadecimal(data[13], hexValues, 30);
    decimalToHexadecimal(data[14], hexValues, 32);
    decimalToHexadecimal(data[15], hexValues, 34);
}

inline void decimalToHexadecimal(uint8_t decimalValue, char* outputBuffer, int currentIndex)
{
    const char hexValues[] = "0123456789abcdef";
    outputBuffer[currentIndex] = hexValues[decimalValue >> 4];
    outputBuffer[currentIndex + 1] = hexValues[decimalValue & 0xf];
}

这工作正常,但我想做一些更有效率的事情,并使用我的输入字符数组直接创建 GUID,如下所示:

GUID CreateGuid(const uint8_t* data)
{
    GUID guid = { 
        *reinterpret_cast<const unsigned long*>(data), 
        *reinterpret_cast<const unsigned short*>(data + 4), 
        *reinterpret_cast<const unsigned short*>(data + 6), 
        *reinterpret_cast<const unsigned char*>(data + 8)
    };
    return guid;
}

这样做时,只设置最后8个字节中的一个,其余为0; 例如使用无符号字符数组 [38, 150, 233, 16, 43, 188, 117, 76, 187, 62, 254, 96, 109, 226, 87, 0]

当我应该得到:

10e99626-bc2b-754c-bb3e-fe606de25700

我得到的是:

10e99626-bc2b-75dc-bb00-000000000000

最佳答案

GUID 是具有简单复制分配的集合。因此,您应该能够直接执行此操作。

GUID CreateGuid(const uint8_t* data)
{
    return *reinterpret_cast<GUID*>(data)
}

关于C++ 从无符号字符数组创建 GUID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68918882/

相关文章:

PHP foreach 循环不按数字顺序获取数组元素?

javascript - 我需要组合 2 个简单数组并删除重复项

arrays - 计算最多包含 k 个奇数的子数组

.net - 同一进程的两个线程可以产生相同的 GUID 吗?

javascript - 如何测试有效的 UUID/GUID?

c++ - 在 Direct2D 中实现一个简单的 lookAt-like 相机

c++ - 错误 C2248 : strange error when I use thread

c++ - 是否可以从 decltype 获取类型?

c++ - 没有 ./a.out 在 g++ 中生成

c# - 为什么 GUID 中的第三个数据以 4 开头?