UNICODE和ASCII

  软件中的字符采用UNICODE方式编码是软件走向国际化的重要一个因素,而且现代很多操作系统默认的字符编码方式都是采用UNICODE的,但是很多的库函数都是采用ASCII编码方式,以及一些第三方库也采用ASCII编码,所以字符需要在UNICODE编码以及ASCII编码之间转换,转换采用sprintf以及windows API实现。

//%s String  When used with sprintf functions, specifies a single-byte–character string; when used with swprintf functions, specifies a wide-character string. Characters are printed up to the first null character or until the precision value is reached.

 
//%S String When used with sprintf functions, specifies a wide-character string; when used with swprintf functions, specifies a single-byte–character string. Characters are printed up to the first null character or until the precision value is reached.

//ascii to unicode 一

 char szbuf[100];
 strcpy(szbuf, "abcdefg");
 wchar_t szw[100];

 swprintf(szw, L"%S", szbuf);

//acii to unicode 二

int MultiByteToWideChar(
  UINT CodePage,         // code page
  DWORD dwFlags,         // character-type options
  LPCSTR lpMultiByteStr, // address of string to map
  int cchMultiByte,      // number of bytes in string
  LPWSTR lpWideCharStr,  // address of wide-character buffer
  int cchWideChar        // size of buffer
);

::MultiByteToWideChar(CP_ACP, 0, szbuf, -1, szw, 100);


//unicode to ascii 一

sprintf(szbuf, "%S", szw);

//unicode to ascii 二

int WideCharToMultiByte(
  UINT CodePage,         // code page
  DWORD dwFlags,         // performance and mapping flags
  LPCWSTR lpWideCharStr, // address of wide-character string
  int cchWideChar,       // number of characters in string
  LPSTR lpMultiByteStr,  // address of buffer for new string
  int cchMultiByte,      // size of buffer
  LPCSTR lpDefaultChar,  // address of default for unmappable
                         // characters
  LPBOOL lpUsedDefaultChar   // address of flag set when default
                             // char. used
);

::WideCharToMultiByte(CP_ACP, 0, szw, -1, szbuf, 100, NULL, NULL);

知道了字符怎样在两种编码之间转换,那怎样编写出既支持unicode编译又支持ascii编译的程序呢?
可以采用_T宏,必须包含TCHAR.H头文件

 //TCHAR.H Routine
 TCHAR szt[100];
 TCHAR sz[] = _T("abcdefg");
 _stprintf(szt, _T("%s"), sz);

#ifdef _UNICODE
 std::wcout << szt << std::endl;
#else
 std::cout << szt << std::endl;
#endif

如果要把TCHAR类型的字符转换成UNICODE编码或者ASCII编码可以采用条件编译,这样代码就既支持unicode编译又支持ascii编译(必须确认是否定义UNICODE宏和_UNICODE宏)

注意:_UNICODE宏用于C运行期头文件,而UNICODE宏则用于Windows头文件

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值