当调用内置的的NSData类的基础框架哈希 - 什么实现用于返回散列值? (CRC32,别的东西吗?)
Answer 1:
别的东西。 其实这是一个实现细节,这并不需要在不同的版本中使用固定算法。
您可以检查在核心基础的开源版本的实现。 需要注意的是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哈希算法 :
#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
文章来源: How does NSData's implementation of the hash method work?