c++ string 转GUID及反转

#include "stdafx.h"
#include <string>
#include <windows.h>

using namespace std;

#define CONVERT_STR_2_GUID(cstr, stGuid) do\
{\
    swscanf_s((const wchar_t*)cstr, L"{%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x}",\
    &(stGuid.Data1),&(stGuid.Data2),&(stGuid.Data3),\
    &(stGuid.Data4[0]),&(stGuid.Data4[1]),&(stGuid.Data4[2]),&(stGuid.Data4[3]),\
    &(stGuid.Data4[4]),&(stGuid.Data4[5]),&(stGuid.Data4[6]),&(stGuid.Data4[7]));\
}while(0);

int _tmain(int argc, _TCHAR* argv[])
{
    const wstring strGuid = L"{9245fe4a-d402-451c-b9ed-9c1a04247482}";
    GUID stGuid = {0};

    CONVERT_STR_2_GUID(strGuid.c_str(), stGuid);

    wprintf_s(L"%s\r\n",strGuid.c_str());
    wprintf_s(L"{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", stGuid.Data1,stGuid.Data2,stGuid.Data3,
        stGuid.Data4[0],stGuid.Data4[1],stGuid.Data4[2],stGuid.Data4[3],
        stGuid.Data4[4],stGuid.Data4[5],stGuid.Data4[6],stGuid.Data4[7]);

    return 0;
}

上面这段程序能看出问题来么? 看出来的兄弟可以在下面指出来!

反正在vs2012及vs2013环境中验证是有问题的。如GUID {9245fe4a-d402-451c-b9ed-9c1a04247482},报下面现象:

---------------------------
Microsoft Visual C++ Runtime Library
---------------------------
Debug Error!

Program: D:\CPP_Pro\GUIDTest\Debug\GUIDTest.exe
Module: D:\CPP_Pro\GUIDTest\Debug\GUIDTest.exe
File:

Run-Time Check Failure #2 - Stack around the variable 'stGuid' was corrupted.

(Press Retry to debug the application)

---------------------------
中止(A) 重试(R) 忽略(I)
---------------------------

暂时记在这,其实还有其它方法可以实现,可以避免上面出错, 如下:

#include "stdafx.h"
#include <string>
#include <windows.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	const wstring strGuid = L"{9245fe4a-d402-451c-b9ed-9c1a04247482}";
	GUID stGuid = {0};

	CLSIDFromString((LPCOLESTR)strGuid.c_str(), (LPCLSID)&stGuid);

	wprintf_s(L"%s\r\n",strGuid.c_str());
	wprintf_s(L"{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", stGuid.Data1,stGuid.Data2,stGuid.Data3,
		stGuid.Data4[0],stGuid.Data4[1],stGuid.Data4[2],stGuid.Data4[3],
		stGuid.Data4[4],stGuid.Data4[5],stGuid.Data4[6],stGuid.Data4[7]);

	return 0;
}

反转就更容易了,可以用sprintf之类的,也可以用StringFromCLSID

参考:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms680589(v=vs.85).aspx

posted on 2015-01-27 23:37 kernel_main 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/kernel0815/p/4254683.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值