Read GUID value stored in registry

时光总嘲笑我的痴心妄想 提交于 2020-01-01 11:34:07

问题


I try to read a GUID value stored as a binary value in registry in Delphi. When I read it with BintoHex, but the result is in reverse order. It seems that I have to swap bytes but I thought BinToHex would do it.

I refered to this thread but I can't find the right solution : how to convert byte array to its hex representation in Delphi It seems that it is due to little Eendian.

Below, you can see the GUID stored in registry

Here is my code :

var
s : string;
buffer : pointer;
...

begin
getmem(buffer, 1024*1024);
....
reg.ReadBinaryData(iValueOfregistry, buffer^, 1024*1024);
....
bintohex(pointer(longint(buffer)+14), PChar(s), 32);

Output for s : 90E24D373F126545916439C4925E467B

GUID should be FOLDERID_Downloads GUID :
{374DE290-123F-4565-9164-39C4925E467B}

Please help


回答1:


A GUID in binary form is best thought of as a record. Indeed in Delphi the record already exists – it is TGUID.

All you need to do is to copy the relevant bytes directly into a variable of type TGUID and your job is done. If you want a string representation, use GUIDToString.

var
  GUID: TGUID;
  strGUID: string;
....
GUID := PGUID(PAnsiChar(buffer)+14)^;
strGUID := GUIDToString(GUID);

This will take care of all the endian issues automatically. Let's take a look at the declaration of TGUID:

TGUID = packed record
  D1: LongWord;
  D2: Word;
  D3: Word;
  D4: array[0..7] of Byte;
end;

Your code treats this as a straight array of bytes. However, in the record, D1, D2 and D3 are integral types on a little endian machine. So your code reverses the first 4 bytes, those belonging to D1. It then reverses the two bytes of D2, and also the two bytes of D3. The array of 8 bytes at the end of the GUID are not reversed, of course.

So, whilst you could readily do all the byte swapping yourself, it's far better to use a record to do so, and take advantage of the helper function that converts a binary GUID record to a properly formatted GUID string.



来源:https://stackoverflow.com/questions/14828410/read-guid-value-stored-in-registry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!