Windows API之Unicode下数据转换
首先mfc下字符串只有两种数据:char(一个字节)和wchar_t(两个字节),很多其他数据类型如TCHAR,WCHAR等都是这个两个基本类型的宏定义,BYTE是uchar。string是使用STL时必不可少的类型,所以是做工程时必须熟练掌握的;char*是从学习C语言开始就已经和我们形影不离的了,有许多API都是以char*作为参数输入的。所以熟练掌握三者之间的转换十分必要。
资料来源:https://blog.csdn.net/lidandan2016/article/details/90260172
1、在UNICODE工程中指定使用多字节版本的API
对话框打印char* 选择 char* info = "Hello World !" ;
::MessageBoxA ( this->m_hWnd, info, "", MB_OK ) ;
2、CString 转 char* .
1)UNICODE工程下使用WSA()
1 int nLen; 2 char * wsabuf = NULL; 3 USES_CONVERSION; 4 wsabuf = W2A(send_txt_str);//send_txt_str为CString消息
2)使用强制转换。
例如:
1 CString theString( "This is a test" ); 2 LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;
3)使用strcpy。
例如:
1 CString theString( "This is a test" ); 2 LPTSTR lpsz = new TCHAR[theString.GetLength()+1]; 3 _tcscpy(lpsz, theString);
4)使用CString::GetBuffer。
例如:
1 CString s(_T("This is a test ")); 2 LPTSTR p = s.GetBuffer(); 3 4 // 在这里添加使用p的代码 5 if(p != NULL) *p = _T('\0'); 6 s.ReleaseBuffer(); 7 8 // 使用完后及时释放,以便能使用其它的CString成员函数 9 CString str = "ABCDEF"; 10 char *pBuf = str,GetBuffer( 0 ); 11 str.ReleaseBuffer();
3、char* 转 CString
直接强制转换, CString.format("%s",char*); CString的Format格式化方法是非常好用的。string的c_str()也是非常常用的,但要注意和char *转换时,要把char定义成为const char*,这样是最安全的。以上函数UNICODE编码也没问题:unicode下照用,加个_T()宏就行了,像这样子_T("%s")
4、_T("AA")转0xAA
BYTE byte1 = wcstol ( _T("AA"), NULL, 16 );
5、_T("你好")转C4 E3 BA C3
用2的方法转char* -> BYTE*, 定义一个循环,在循环中定义一个临时CString变量Format取出单个BYTE元素
6、字符串转整数
“ff”、_T("ff")转256
用atoi那一系列函数(a代表ascii,to代表转化,i代表int)
同上还有itoa一系列函数
ttoi(), CString转整数
使用strtol系列函数:(str to long)
1 int a; 2 CString str; 3 str=_("1234"); 4 a=wcstol(str,NULL,10); 5 a->1234
temp="123456";
1)短整型(int)
i = atoi(temp);
2)长整型(long)
l = atol(temp);
3)浮点(double)
d = atof(temp);
string s; d= atof(s.c_str());
4)BSTR变量
BSTR bstrValue = ::SysAllocString(L"程序员");
...///完成对bstrValue的使用
SysFreeString(bstrValue);
5)CComBSTR变量
CComBSTR类型变量可以直接赋值
CComBSTR bstrVar1("test");
CComBSTR bstrVar2(temp);
6)_bstr_t变量
_bstr_t类型的变量可以直接赋值
_bstr_t bstrVar1("test");
_bstr_t bstrVar2(temp);
7、_T("01FF")转十进制:511
long a = wcstol (_T("01FF"), NULL, 16); //a=511
8、整数转字符串
_ltoa
9、把整数的十六进制转化成CString
1 int a=20; 2 CString temp_str; 3 temp_str.Format(_T("%02x"),20);
10、CString -> string
GetBuffer()后一定要ReleaseBuffer(),否则就没有释放缓冲区所占的空间.