gpt4 book ai didi

nsdata - NSData 的 hash 方法的实现是如何工作的呢?

转载 作者:行者123 更新时间:2023-12-02 22:41:00 24 4
gpt4 key购买 nike

在基础框架中对内置的 NSData 类调用散列时——使用什么实现来返回散列值? (CRC32,还有什么?)

最佳答案

别的。其实就是一个实现细节,不需要在不同的版本中使用固定的算法。

你可以在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

关于nsdata - NSData 的 hash 方法的实现是如何工作的呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10768467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com