我正在使用 firebase firestore,出于某種原因,我需要將每個新用戶檔案 ID 散列到整數,特別是16Bit UTF integer。主要是嘗試在 Dart中復制.hashcode方法。
我發現并嘗試過的是這個
// Convert to 32bit integer
const hashFunction = (string) => {
var hash = 0;
if (string.length == 0) return hash;
for (i = 0; i < string.length; i ) {
char = string.charCodeAt(i);
hash = (hash << 5) - hash char;
hash = hash & hash;
}
return hash >>> 0; // returns hash as positive integer
};
但這只能轉換為 32 位 int。任何和所有的幫助表示贊賞。
EDIT1:使用@selbie 的更改我取得了一些進展,但我得到的散列與 Dart 中的 .hashCode 方法完全不同
,
無論如何我可以得到相同的結果嗎
uj5u.com熱心網友回復:
如果您只想要 16 位哈希,則:
取而代之的是:
return hash >>> 0; // returns hash as positive integer
這:
return hash & 0xffff; // return lower 16-bits of hash value
這一行:
if (string.length == 0) return hash;
不需要,因為如果 string.length 為 0,您的 for 回圈將不會運行。
最后,讓變數名與型別相同并不是一個好主意。所以讓我們重命名string為s.
這是一個簡化的解決方案:
const hashFunction = (s) => {
var hash = 0;
for (i = 0; i < s.length; i ) {
hash = (hash << 5) - hash s.charCodeAt(i);
hash = hash & hash; // prevent overflow from happening
}
return hash & 0xffff; // returns lower 16-bit of hash value
};
考慮到這一點,16 位散列并不是很強的散列。在散列幾千個字串后肯定會發生沖突。根據需要考慮加密強散列或更大的散列寬度。
uj5u.com熱心網友回復:
function hashcode(string) {
let hash = 0;
for (let length = string.length, index = 0; index < length; index) {
hash = hash string.charCodeAt(index) & 0x1fffffff;
hash = hash ((hash & 0x7ffff) << 10) & 0x1fffffff;
hash ^= hash >> 6;
}
hash = hash ((hash & 0x3ffffff) << 3) & 0x1fffffff;
hash ^= hash >> 11;
return hash ((hash & 0x3fff) << 15) & 0x1fffffff;
}
來自https://www.dartpad.dev/scripts/playground.dart.js第 6107 行
https://github.com/dart-lang/sdk/blob/main/sdk/lib/_internal/js_runtime/lib/js_string.dart#L448
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/402031.html
標籤:javascript 散列 哈希码 utf-16 16 位
上一篇:在Vue3中改變根狀態停止作業
