宽字符wchar_t *转char *的方法

在做项目的时候需要把宽字符转一个多字符,于是在查阅资料后有了以下的方法:

//参数: lpWideCharStr 需要转化的宽字符串 lpMultiByteStr 转换后的结果 cwcChars需要转换的字节数,-1代表转换整个宽字符 返回值 转换了多少个字节
int unicodeToUtf8 ( const wchar_t* lpWideCharStr, char* lpMultiByteStr, int cwcChars )
 {
	 const unsigned short*   pwc = (unsigned short *)lpWideCharStr;
	 unsigned char*          pmb = (unsigned char  *)lpMultiByteStr;
	 const unsigned short*   pwce;
	 unsigned int  cBytes = 0;

	 if ( cwcChars >= 0 ) 
	 {
		 pwce = pwc + cwcChars;
	 } 
	 else 
	 {
		 pwce = (unsigned short *)((unsigned long)-1);
	 }

	 while ( pwc < pwce ) 
	 {
		 unsigned short  wc = *pwc++;

		 if ( wc < 0x00000080 ) 
		 {
			 *pmb++ = (char)wc;
			 cBytes++;
		 } 
		 else
		 {
			 if ( wc < 0x00000800 ) 
			 {
				 *pmb++ = (char)(0xC0 | ((wc >>  6) & 0x1F));
				 cBytes++;
				 *pmb++ = (char)(0x80 |  (wc        & 0x3F));
				 cBytes++;
			 } 
			 else
			 {
				 if ( wc < 0x00010000 ) 
				 {
					 *pmb++ = (char)(0xE0 | ((wc >> 12) & 0x0F));
					 cBytes++;
					 *pmb++ = (char)(0x80 | ((wc >>  6) & 0x3F));
					 cBytes++;
					 *pmb++ = (char)(0x80 |  (wc        & 0x3F));
					 cBytes++;
				 }  
			 }
		 }
			 
		if ( wc == L'\0' )
			return cBytes;
	 }

	 return cBytes;
 }

另外也可以使用库函数 WideCharToMultiByte(windows下使用),wcstombs(unix下使用c语言库),但是我在max osx 64位应用程序中使用wcstombs提示不能转换,最后采取上面的方法,注意在64位下下面代码的long不能换成int,32为下可以,原因大家都应该知道吧。
pwce = (unsigned short *)((unsigned long)-1);



你可能感兴趣的:(Mac,OSX开发)