【问题标题】:iconv : Converting from UTF-16LE to UTF-8 terminates in middle of the stringiconv :从 UTF-16LE 转换为 UTF-8 在字符串中间终止
【发布时间】:2013-06-28 07:22:25
【问题描述】:

我有一个 UTF-16LE 字符串“TEST”及其 hexdump,如下所示

feff 0074 0065 0073 0074 000a

如果我在 bash 上使用命令 iconv 将此字符串转换为 UTF-8,那么它会在没有任何问题的情况下进行转换。

6574 7473 000a

但是,如果我对我的 C 程序执行相同的操作,那么一旦遇到带有字符“T”的 0x00,iconv 函数似乎将其视为空终止,即使我已将字符串长度指定为12(包括 bom 和 null 终止)。

65 000a

下面是我正在测试的代码。但是,如果我转换任何大小的宽字符字符串(中间没有 0x00 字节)将返回正确的输出。

char *cOutput;    // Output buffer with more enough size required
size_t tOutput; 
char *cInput;     // string wide characters
size_t tInput;
iconv_t cd;

........

cd = iconv_open("UTF8//TRANSLIT", "UTF-16LE");
iconv(cd, &cInput, &tInput, &cOutput, &tOutput);

这个问题是否有任何解决方案,或者我做错了什么?任何意见将不胜感激。

【问题讨论】:

  • 一行代码价值1000多字。显示您的代码。
  • 正如 H2CO3 所说,显示更多代码,例如如何初始化数据和大小。

标签: c iconv


【解决方案1】:

猜测,您的问题是您初始化 tInput 不正确,可能使用了 strlen(cInput)

这段代码为我产生了预期的输出:

#include <stdio.h>
#include <string.h>
#include <iconv.h>

int main()
{
    char utf16le_str[] = { '\xff', '\xfe', '\x74', '\x00', '\x65', '\x00',
        '\x73', '\x00', '\x74', '\x00', '\x0a', '\x00' };
    char dest_str[100];
    char *in = utf16le_str;
    char *out = dest_str;
    size_t inbytes = sizeof utf16le_str;
    size_t outbytes = sizeof dest_str;
    iconv_t conv = iconv_open("UTF-8//TRANSLIT", "UTF-16LE");

    if (conv == (iconv_t)-1) {
        perror("iconv_open");
        return 1;
    }

    if (iconv(conv, &in, &inbytes, &out, &outbytes) == (size_t)-1) {
        perror("iconv");
        return 1;
    }

    dest_str[sizeof dest_str - outbytes] = 0;
    puts(dest_str);

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 2018-09-07
    • 2013-11-14
    相关资源
    最近更新 更多