2013-08-27 292 views
1

好吧,我哈希一个图像。正如你所知道的,哈希图像需要FOREVER。所以我拍摄了100个图像样本,均匀分布。这是代码。从const void转换为char?

#define NUM_HASH_SAMPLES 100 

@implementation UIImage(Powow) 

-(NSString *)md5Hash 
{ 
    NSData *data = UIImagePNGRepresentation(self); 

    char *bytes = (char*)malloc(NUM_HASH_SAMPLES*sizeof(char)); 
    for(int i = 0; i < NUM_HASH_SAMPLES; i++) 
    { 
     int index = i*data.length/NUM_HASH_SAMPLES; 

     bytes[i] = (char)(data.bytes[index]); //Operand of type 'const void' where arithmetic or pointer type is required 
    } 

    unsigned char result[CC_MD5_DIGEST_LENGTH]; 
    CC_MD5(bytes, NUM_HASH_SAMPLES, result); 
    return [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] 
      ]; 
} 

错误发生在注释行上。

我在做什么错?

回答

4

data.bytes是一个void *,所以它是没有意义的取消引用它(甚至执行必要的指针算法)。

所以,如果你的意思是把一个字节出来的数据,然后获得一个指向const unsigned char和解引用是:

const unsigned char *src = data.bytes; 
/* ..then, in your loop.. */ 
bytes[i] = src[index]; 

哦,do not cast the return value of malloc()

+0

谢谢!但是,我发现做bytes [i] =&data.bytes [index]的时候有点干净。我的计算机科学教授告诉我,施放malloc是个好习惯。去搞清楚。 – rweichler

+0

@rweichler他错了。此外,代码看起来不正确... – 2013-08-28 12:03:35

1

根据NSData的文档,data.bytes返回一个类型const void *。基本上,你试图访问一个指向void的指针,这是没有意义的,因为void没有大小。

将其转换为char指针并将其解引用。

((const char *)data.bytes)[index]

*((const char *)data.bytes + index)

编辑:我通常做的是什么指针赋值给一个已知的数据类型直线距离并使用它。

I.e.

const char *src = data.bytes; 
bytes[i] = src[index]; 

EDIT2:您还可能要离开由H2CO3作为建议const预选赛。这样你就不会意外地写到你不应该去的地方。

+0

甚至更​​好:'((const char *)data.bytes)[index]';甚至稍微好一点:'((const const unsigned char *)data.bytes)[index]'完美:'const unsigned char * bytes = data.bytes;字节[指数];' – 2013-08-27 08:51:47