这是上一个问题的后续问题
该问题中的问题已解决,现在代码按预期进行,但是 utf-8 到 ucs2 转换的最终输出是乱码。我的意思是最终文本的十六进制值无论如何都与 utf-8 版本不对应。我知道它们是不同的编码,但两者之间似乎没有任何映射。
转换的输入是“ĩ”,输出是“ÿþ)^A”。在十六进制中,“ĩ”(utf-8 值)的值为 c4a9,“ÿþ)^A”(ucs2 值)的值为“00FF 00FE 0029 0001”。
我希望有人对此行为有解释,或者可以告诉我我在代码中做错了什么。
新更新的代码是:
UErrorCode resultCode = U_ZERO_ERROR;
UConverter* pLatinOneConv = ucnv_open("ISO-8859-1", &resultCode);
// Change the callback to error out instead of the default
const void* oldContext;
UConverterFromUCallback oldFromAction;
UConverterToUCallback oldToAction;
ucnv_setFromUCallBack(pLatinOneConv, UCNV_FROU_CALLBACK_STOP, NULL, &oldFromAction, &oldContext, &resultCode);
ucnv_setToUCallBack(pLatinOneConv, UCNV_TO_U_CALLBACK_STOP, NULL, &oldToAction, &oldContext, &resultCode);
int32_t outputLength = 0;
int bodySize = uniString.length();
int targetSize = bodySize * 4;
char* target = new char[targetSize];
printf("Body: %s\n", uniString.c_str());
if (U_SUCCESS(resultCode))
{
outputLength = ucnv_fromAlgorithmic(pLatinOneConv, UCNV_UTF8, target, targetSize, uniString.c_str(),
uniString.length(), &resultCode);
ucnv_close(pLatinOneConv);
}
printf("ISO-8859-1 just tried to convert '%s' to '%s' with error '%i' and length '%i'", uniString.c_str(),
outputLength ? target : "invalid_char", resultCode, outputLength);
if (resultCode == U_INVALID_CHAR_FOUND || resultCode == U_ILLEGAL_CHAR_FOUND || resultCode == U_TRUNCATED_CHAR_FOUND)
{
if (resultCode == U_INVALID_CHAR_FOUND)
{
resultCode = U_ZERO_ERROR;
printf("Unmapped input character, cannot be converted to Latin1");
// segment Text, if necessary, and add UUIDs copy existing pPdu's addresses and optionals
UConverter* pUscTwoConv = ucnv_open("UCS-2", &resultCode);
if (U_SUCCESS(resultCode))
{
printf("Text Body: %s\n", uniString.c_str());
outputLength = ucnv_fromAlgorithmic(pUscTwoConv, UCNV_UTF8, target, targetSize, uniString.c_str(),
uniString.length(), &resultCode);
ucnv_close(pUscTwoConv);
}
printf("UCS-2 just tried to convert '%s' to '%s' with error '%i' and length '%i'", uniString.c_str(),
outputLength ? target : "invalid_char", resultCode, outputLength);
if (U_SUCCESS(resultCode))
{
pdus = SegmentText(target, pPdu, SEGMENT_SIZE_UNICODE_MAX, true);
}
}
else
{
printf("DecodeText(): Text contents does not appear to be valid UTF-8");
}
}
else
{
printf("DecodeText(): Text successfully converted to Latin1");
std::string newBody(target, outputLength);
pdus = SegmentText(newBody, pPdu, SEGMENT_SIZE_MAX);
}