使用ICU库从UTF-16到UTF-8

使用ICU库从UTF-16到UTF-8,utf-8,utf-16,icu,Utf 8,Utf 16,Icu,我想把UTF-16字符串转换成UTF-8。我通过Unicode偶然发现了ICU图书馆。我在进行转换时遇到问题,因为默认值为UTF-16。 我尝试过使用转换器: UErrorCode myError = U_ZERO_ERROR; UConverter *conv = ucnv_open("UTF-8", &myError); int32_t bytes = ucnv_fromUChars(conv, target, 0, (UChar*)source, numread, &m

我想把UTF-16字符串转换成UTF-8。我通过Unicode偶然发现了ICU图书馆。我在进行转换时遇到问题,因为默认值为UTF-16。 我尝试过使用转换器:

UErrorCode myError = U_ZERO_ERROR;
UConverter *conv = ucnv_open("UTF-8", &myError);
int32_t bytes = ucnv_fromUChars(conv,   target, 0, (UChar*)source, numread, &myError);
char *targetLimit = target + reqdLen;
const UChar *sourceLimit = mySrc + numread;
ucnv_fromUnicode(conv,&target, targetLimit, &mySrc, sourceLimit, NULL, TRUE, &myError);
我得到的字节为-(大随机数) 和原始目标位置的垃圾


我遗漏了什么?

在指定UErrorCode参数的调用之后检查错误是最佳做法。我会从那里开始

类似于

if (U_FAILURE(status)) 
{
    std::cout << "error: " << status << ":" << u_errorName(status) << std::endl;
}
if(U_故障(状态))
{

std::我忘了提到UTF-16预计在小端或大端