【发布时间】:2021-08-25 07:50:26
【问题描述】:
我有一个函数,它将一个 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}
【问题讨论】:
-
也许使用
sprintf -
@Bodo 仍然会从我的 unsigned char 数组创建一个字符串,而不是直接使用 unsigned char 数组
标签: c++ arrays guid unsigned-char