简体   繁体   中英

Implicit conversion loses integer precision in ZLib compression method

Implicit conversion loses integer precision: 'unsigned long' to 'uInt' (aka 'unsigned int')

I am trying to update my application from 32bit to 64bit, since changing the architecture I have recived an error as decribed above.

I have a method that takes NSData that is zlib compressed and returns the decomrepssed data.

This is the method.

- (NSData*) dataByDecompressingData:(NSData*)data {

     NSLog(@"%lu", (unsigned long)data.length);

    Byte* bytes = (Byte*)[data bytes];
    NSInteger len = [data length];
    NSMutableData *decompressedData = [[NSMutableData alloc] initWithCapacity:COMPRESSION_BLOCK];
    Byte* decompressedBytes = (Byte*) malloc(COMPRESSION_BLOCK);

    z_stream stream;
    int err;
    stream.zalloc = (alloc_func)0;
    stream.zfree = (free_func)0;
    stream.opaque = (voidpf)0;

    stream.next_in = bytes;
    err = inflateInit(&stream);
    CHECK_ERR(err, @"inflateInit");

    while (true) {
        stream.avail_in = len - stream.total_in; // this is where the error happens the yellow triangle is under the "minus" -
        stream.next_out = decompressedBytes;
        stream.avail_out = COMPRESSION_BLOCK;
        err = inflate(&stream, Z_NO_FLUSH);
        [decompressedData appendBytes:decompressedBytes length:(stream.total_out-[decompressedData length])];
        if(err == Z_STREAM_END)
            break;
        CHECK_ERR(err, @"inflate");
    }

    err = inflateEnd(&stream);
    CHECK_ERR(err, @"inflateEnd");

    free(decompressedBytes);
    return decompressedData;
}

I am not sure how to fix this. I have tried to type cast len using (int) however this still dose not work. .

That's not an error, it's a warning. And if you'd like to silence it, you can simply cast the unsigned long portion of your expression to an unsigned int :

stream.avail_in = (uint)(len - stream.total_in);

The warning simply alerts you to the fact that you're turning a long into an int, thus losing precision; and since you haven't explicitly cast your long into an int, your compiler's just letting you know that maybe you're losing precision unintentionally.

You can easily silence the warning as Lyndsey points out. However, to be complete as well as sufficiently paranoid, you should either verify that len is less than or equal to the maximum unsigned value (you can simply assign it to an unsigned and see if it's still equal to len ), or you can add an outer loop to process UINT_MAX chunks of the input data at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM