在仍使用XCode 3的项目中(没有像Codecvt这样的C ++ 11功能)

最佳答案

使用转换库,例如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);

07-26 06:04