在Mac上将UTF16字符串转换为wchar_t的正确方法是什么?

What is the right way to convert UTF16 string to wchar_t on Mac?

本文关键字:方法 是什么 wchar 上将 Mac UTF16 字符串 转换      更新时间:2023-10-16

在仍然使用XCode 3的项目中(没有c++ 11的功能,如codecvt)

使用转换库,如libiconv。您可以根据需要将其输入编码设置为"UTF-16LE""UTF-16BE",并将其输出编码设置为"wchar_t",而不是任何特定的字符集。

#include <iconv.h>
uint16_t *utf16 = ...; // input data
size_t utf16len = ...; // in bytes
wchar_t *outbuf = ...; // allocate an initial buffer
size_t outbuflen = ...; // in bytes
char *inptr = (char*) utf16;
char *outptr = (char*) outbuf;
iconv_t cvt = iconv_open("wchar_t", "UTF-16LE");
while (utf16len > 0)
{
    if (iconv(cvt, &inptr, &utf16len, &outptr, &outbuflen) == (size_t)(−1))
    {
        if (errno == E2BIG)
        {
            // resize outbuf to a larger size and
            // update outptr and outbuflen according...
        }
        else
            break; // conversion failure
    }
}
iconv_close(cvt);

为什么要在mac上安装wchar_t ?wchar_t不一定是16位,它在mac上不是很有用。

我建议转换你的NSString使用

char* payload; // point to string with UTF16 encoding
NSString* s = [NSString stringWithCString:payload encoding: NSUTF16LittleEndianStringEncoding];

将NSString转换为UTF16

const char* payload = [s cStringUsingEncoding:NSUTF16LittleEndianStringEncoding];

请注意mac也支持NSUTF16BigEndianStringEncoding

注意2:虽然使用了const char*,但数据是用UTF16编码的,所以不要将其传递给strlen()

我会走最安全的路线。

  1. 获取UTF-16字符串作为UTF-8字符串(使用NSString)
  2. 设置区域设置为UTF-8
  3. 使用mbstowcs()将UTF-8多字节字符串转换为wchart_t

每一步都确保字符串值将被保护