MFC CString与GUID结构体之间相互转换

简介

MFC编程时,注册表里存储的GUID都是字符串类型的,形如:

00000000-0000-0000-0000-000000000000

的表现形式。

而在代码里,经常需要把这个字符串形式的GUID转换成结构体,形如:

typedef struct _GUID {
    unsigned long  Data1;
    unsigned short Data2;
    unsigned short Data3;
    unsigned char  Data4[ 8 ];
} GUID;

转换函数

CString GuidToCstring(GUID *pGuid)
{
    CString str;
    str.Format("%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
		pGuid->Data1,
		pGuid->Data2,
		pGuid->Data3,
		pGuid->Data4[0],
		pGuid->Data4[1],
		pGuid->Data4[2],
		pGuid->Data4[3],
		pGuid->Data4[4],
		pGuid->Data4[5],
		pGuid->Data4[6],
		pGuid->Data4[7]);
    return(str);
}

int CStringToGUID(CString str_guid, GUID *guid) {

	int len = str_guid.GetLength();
	if (len != 36)
		return NULL;

	int i;
	char cp;
	for (i = 0; i < 36; i++) {
		cp = str_guid.GetAt(i);
		if ((i == 8) || (i == 13) || (i == 18) || (i == 23)) {
			if (cp == '-')
				continue;
			return -1;
		}

		if (!isxdigit(cp))
			return -1;
	}

	guid->Data1 = strtoul(str_guid.Left(8), NULL, 16);
	guid->Data2 = (unsigned short)strtoul(str_guid.Mid(9, 4), NULL, 16);
	guid->Data3 = (unsigned short)strtoul(str_guid.Mid(14, 4), NULL, 16);
	
	int j;
	for (i = 19, j = 0; i < 23; i += 2, j++) {
		guid->Data4[j] = (unsigned char)strtoul(str_guid.Mid(i, 2), NULL, 16);
	}

	for (i = 24, j = 2; i < 36; i += 2, j++) {
		guid->Data4[j] = (unsigned char)strtoul(str_guid.Mid(i, 2), NULL, 16);
	}

	return 0;
}

如上代码,可以适用于MFC编程。
一通百通,上述代码也可以很容易的改成任何语言的GUID转换函数。

你可能感兴趣的:(C/C++应用,windows操作系统,mfc,c++)