2013-08-27 233 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