问题
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_MAX
to 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