我爱你
我已经知道它的内容是“我爱你”,内码为0x6211,0x7231,0x4f60的unicode串就是“我爱你” 我已经知道用WideCharToMultiByte把内码为0x6211,0x7231,0x4f60的unicode串转换成ANSI的字符串,但如何把 char buf[32]="我爱你"转换成内码为0x6211,0x7231,0x4f60的unicode串? 直接定义我知道可以这样: unsigned short u_str[10]; u_str[0]=0x6211; u_str[1]=0x7231; u_str[2]=0x4f60;
但我要能用一段代码把buf这个char串转换成u_str这个unsigned short串; 请各位大虾指点!
char buf[32]="我爱你"; char tmp[5] = {0, 0,0,0,0}; unsigned short u_str[10]; for(int i = 0; i < 3; i++) { memcpy(tmp, buf + 8 * i+3, 4); u_str[i] = (unsigned short)strtol(tmp, NULL, 16); }
一步一步来,先分析字符串,得到wchar_t, then...
既已用 WideCharToMultiByte , 若想反取之, 则请用 MultiByteToWideChar
TCHAR lpsz[]=_T("我爱你我爱你");
int nlpsz=sizeof(lpsz)-1; //测试字符串的长度,不包含\0 int nWbufferlen=(nlpsz/8)+1;//保存该unicode字符串的WCHAR缓冲区长度,不是字节长度
WCHAR *wsz2=new WCHAR[nWbufferlen]; memset(wsz2,0,nWbufferlen*sizeof(WCHAR));
int nwsz2=nlpsz/8;//unicode字符串的长度,不包含\0\0 for(int i=0;i<nwsz2;i++) { char * endptr=NULL; unsigned long nOut=_tcstoul(&(lpsz[i*8+3+0]),&endptr,16); wsz2[i]=(unsigned short)nOut; }
int nResultBufferlen=nwsz2*(sizeof(WCHAR)/sizeof(TCHAR))+1; //保存TCHAR结果的字符串缓冲区字节长度 TCHAR *lpszResult=new TCHAR[nResultBufferlen]; memset(lpszResult,0,nResultBufferlen); //转换unicode to gb2312 WideCharToMultiByte( CP_ACP, 0, wsz2, -1, lpszResult, nResultBufferlen, NULL, NULL ); TRACE ("unicode-->GB2312:%s\n",lpszResult);
delete[] lpszResult; delete[] wsz2;
上述代码,之所以没有用_tcslen或者wcslen,因为考虑到如果习惯使用Run Time lib的字符串操作函数,在线程中使用不安全。更多情况下习惯于操作缓冲区,或者使用platform sdk中的safe string来进行操作字符串
mark
感谢谢各位! lfchen(一条晚起的虫)的代码正是我想要的!
|