开发者

why iconv read more bytes than i specified

开发者 https://www.devze.com 2023-03-10 02:56 出处:网络
I use size_t iconv(i开发者_开发问答conv_t cd,char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft);

I use

size_t iconv(i开发者_开发问答conv_t cd,   char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft);

to convert UTF-16BE to GB2312.

inbytesleft is bytes number to be convert. After conversion, inbytesleft is bytes number of not converted.

After one call, I found inbytesleft is -2, according to iconv man page this function should read at most inbytesleft. Who can tell my why and how to fix this?

code to be convert is

"保单验证"

Thanks


How are you getting the input data into your program?

I've tested the situation using this code and it seems to work:

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

int main(){
    char data[10] = {0x4f,0xdd,0x53,0x55,0x9a,0x8c,0x8b,0xc1, 0, 0};
    char outdata[20];
    char *dataptr;
    char *outdataptr;
    iconv_t cd;
    size_t result;
    size_t inbytesleft = 8;
    size_t outbytesleft = 20;
    int i;

    cd = iconv_open("GB2312", "UTF-16BE");
    dataptr = data;
    outdataptr = outdata;
    result = iconv(cd, &dataptr, &inbytesleft, &outdataptr, &outbytesleft);
    if(result == -1)
        printf("Error: %d\n", errno);
    printf("      result: %zd\n", result);
    printf(" inbytesleft: %zd\n", inbytesleft);
    printf("outbytesleft: %zd\n", outbytesleft);

    for(i = 20; i > outbytesleft; i--){
        if(i != 20)
            printf(",");
        printf("0x%02x", *((unsigned char *)&(outdata[20-i])));
    }
    printf("\n");

    return 0;
}

It prints

      result: 0
 inbytesleft: 0
outbytesleft: 12
0xb1,0xa3,0xb5,0xa5,0xd1,0xe9,0xd6,0xa4

Which appears to be correct.

The array of items in the variable data is the UTF-16BE encoding of 保单验证

If this doesn't help, could you post your code for analysis?

0

精彩评论

暂无评论...
验证码 换一张
取 消