2012-05-26 34 views

回答

5

別的東西。實際上它是一個實現細節,不需要在不同版本中使用固定算法。

您可以檢查Core Foundation的開源版本中的實現。請注意,NSData是免費橋接到CFDataRef。從http://opensource.apple.com/source/CF/CF-635.21/CFData.c

static CFHashCode __CFDataHash(CFTypeRef cf) { 
    CFDataRef data = (CFDataRef)cf; 
    return CFHashBytes((uint8_t *)CFDataGetBytePtr(data), __CFMin(__CFDataLength(data), 80)); 
} 

我們看到,前80個字節來計算哈希值。函數CFHashBytes的實現方式如下:使用ELF hash algorithm

#define ELF_STEP(B) T1 = (H << 4) + B; T2 = T1 & 0xF0000000; if (T2) T1 ^= (T2 >> 24); T1 &= (~T2); H = T1; 

CFHashCode CFHashBytes(uint8_t *bytes, CFIndex length) { 
    /* The ELF hash algorithm, used in the ELF object file format */ 
    UInt32 H = 0, T1, T2; 
    SInt32 rem = length; 
    while (3 < rem) { 
    ELF_STEP(bytes[length - rem]); 
    ELF_STEP(bytes[length - rem + 1]); 
    ELF_STEP(bytes[length - rem + 2]); 
    ELF_STEP(bytes[length - rem + 3]); 
    rem -= 4; 
    } 
    switch (rem) { 
    case 3: ELF_STEP(bytes[length - 3]); 
    case 2: ELF_STEP(bytes[length - 2]); 
    case 1: ELF_STEP(bytes[length - 1]); 
    case 0: ; 
    } 
    return H; 
} 

#undef ELF_STEP