iOS 7.1 CommonCrypto library complains: Implicit conversion loses integer precision: 'NSUInteger' (unsigned long) to CC_LONG (unsigned int)

蓝咒 提交于 2019-12-10 16:16:35

问题


I get the above error (in title) whilst doing a MD5 from file.. I can usually cope with these type of 32->64bit conversion issues..but in this case, I do not know what I should do as CC_MD5 is part of CommonCrypto->CommonDigest, a library that ships with iOS7.1. I am assuming [inputData length] is returning NSUInteger and therein lies the issue, however can I simply cast down from UL to UI? I will possibly lose precision if the file is large. Why would a library that Apple ships with require int in a 64 bit capable language such as iOS? Did someone overlook something or am I being really stupid and mis-diagnosing the problem?

- (NSString*) getMD5FromFile:(NSString *)pathToFile {
    unsigned char outputData[CC_MD5_DIGEST_LENGTH];

    NSData *inputData = [[NSData alloc] initWithContentsOfFile:pathToFile];
    CC_MD5([inputData bytes], [inputData length], outputData);
    [inputData release];

    NSMutableString *hash = [[NSMutableString alloc] init];

    for (NSUInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [hash appendFormat:@"%02x", outputData[i]];
    }

    return [hash autorelease];
}

From CommonCrypto->CommonDigest.h:

extern unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md)

I filed bug report with apple (#17256918) but isn't there a way to do this without the error?


回答1:


You simply need to cast [inputData length] to either int or uint32_t as you suspect.

If you want to assert that number is not too large for type you can use the UINT32_MAXto check. Here is an example on an NSAssert you could use.

    NSAssert([inputData length] < UINT32_MAX, @"too big!");



回答2:


I'm not a pro but I hope I didn't make a huge mistake. For code to be a bit safer than just casting without assertion you can use this assert:

NSAssert([inputData length] <= (CC_LONG)-1, @"Input length is too big for unsigned CC_LONG type! Or CC_LONG became signed, which is unlikely");

This variant is better because it doesn't rely on UINT32_MAX, because CC_LONG can be changed in future.

P.S. I was going crazy when I first saw this trick (CC_LONG)-1 some years ago before I realized that it's just type casting and not a sophisticated C feature related to sizeof. So this is a huge relieve for your brain if you struggled with it)



来源:https://stackoverflow.com/questions/24148817/ios-7-1-commoncrypto-library-complains-implicit-conversion-loses-integer-precis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!