从NSData计算iPhone上的校验和 [英] Compute a checksum on the iPhone from NSData

查看:194
本文介绍了从NSData计算iPhone上的校验和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用iPhone SDK,我让用户从图像选择器中选择图像。如果用户选择之前选择的图像,我想让用户知道它。

Using the iPhone SDK, I'm having the user select images from the image picker. If the user selects an image they've selected before, I'd like to make the user aware of it.

我的初步计划(只是为了确保其他工作正常现在)是将图像保存到文件(由于其他原因需要这样做),使用NSData的校验和作为文件名。然后,当他们稍后选择相同的图像时,校验和将是相同的,因此我可以看到具有该名称的文件已经存在 - 欢呼!

My initial plan (just to make sure other things work for now) is to save the image to a file (need to do this anyway for other reasons), using a checksum of the NSData as the filename. Then, when they select the same image later on, the checksum will be the same and so I can see that a file with that name already exists - hurrah!

但是,我已经浏览了互联网和Apple文档,了解如何从NSData计算校验和。我知道我可以实现自己的实现,但如果可能的话,我宁愿避免这样做。我也很高兴有关如何检查两个UIImages是否相同的其他想法。

However, I've scoured the internet and the Apple docs for how to compute a checksum from a NSData. I know I could implement my own implementation, but I'd prefer to avoid that, if possible. I'm also happy for other ideas of how to check that two UIImages are the same.

编辑

两年前,我承诺了一个代码示例,就在这里。真的很抱歉延误! :)

Two years ago I promised a code sample, and here it is. Really sorry for the delay! :)

+(NSString*)imageIdForData:(NSData*)data
{
        char* result = (char*) [[data MD5Sum] bytes];

        NSString* hash =  [NSString stringWithFormat: @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                                           result[0], result[1],
                                           result[2], result[3],
                                           result[4], result[5],
                                           result[6], result[7],
                                           result[8], result[9],
                                           result[10], result[11],
                                           result[12], result[13],
                                           result[14], result[15]];

        return hash;
}


推荐答案

< CommonCrypto / CommonDigest.h> 头文件应该有一个CC_MD5函数,它将计算任意数据的MD5哈希值。它是一个C函数,所以它不能直接在NSData上工作,但它应该可以满足您的需要。

In the <CommonCrypto/CommonDigest.h> header file there should be a CC_MD5 function that will compute an MD5 hash of arbitrary data. It's a C function, so it won't work directly on an NSData, but it should do what you need.

更多 info here (包括使用NSString的包装器 - 应该很容易转换为使用NSData)

Some more info here (including a wrapper using NSString - should be easy enough to convert to use NSData)

这篇关于从NSData计算iPhone上的校验和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆