Long lasting hash from string on iOS and Android
I have a requirement for hash strings for a long time on both iOS and Android. Be sure to have the same results for the same row on both platforms.
The code I'm using on iOS:
+ (long long)hashString:(NSString *)stringToHash
{
if (stringToHash.length == 0)
return -1;
//cr: resolve the warnings here
const unsigned char* str = [stringToHash UTF8String];
int hash = 5381;
int c;
while ((c = *str++)) hash = ((hash << 5) + hash) + c;
bool isNegative = (hash < 0);
hash = abs(hash);
long long lhash = (long)hash;
long long mask = 1;
mask <<= 31;
if (isNegative) lhash |= mask;
return lhash;
}
For Android I am using this code (c code converted to Java):
public static long doHash(String value) {
if (TextUtils.isEmpty(value)) {
return -1;
}
int hash = 5381;
for (int i = 0; i < value.length(); i++) {
hash = ((hash << 5) + hash) + value.charAt(i);
}
boolean isNegative = (hash < 0);
hash = Math.abs(hash);
long lHash = (long) hash;
long mask = 1;
mask <<= 31;
if (isNegative) { lHash |= mask; }
return lHash;
}
In general everything works fine, but sometimes in Android I have a problem where I get a different hash value for the same string.
For example:
doHash("Saved Tap"); returns β 3598946179
doHash("Saved Tap"); returns β 3433737033
I am getting these values ββfrom logs from devices there ... Can't reproduce on devices that I have.
Does anyone see bugs in Java code that could cause this problem? Could it be Java version or Android version?
Thank,
+3
source to share
No one has answered this question yet
Check out similar questions: