// 创建一个简单的哈希函数,使用 JavaScript 实现
function hash(input) {
let hash = 0;
if (input.length === 0) return hash;
for (let i = 0; i < input.length; i++) {
const char = input.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash |= 0; // 转换为32位整数
}
return hash;
}
// 示例用法
const inputString = "Hello, world!";
const hashedValue = hash(inputString);
console.log(`输入: ${inputString}`);
console.log(`哈希值: ${hashedValue}`);
// 解释:
// 这个哈希函数通过遍历输入字符串的每个字符,并使用移位和加法操作来生成一个唯一的哈希值。
// 每次循环中,当前字符的 ASCII 码被添加到哈希值中,并且哈希值会左移五位并减去自身,
// 最后通过 `hash |= 0` 将结果限制为32位整数。这个方法可以确保生成的哈希值具有较好的分布性。
上一篇:nodejs api
下一篇:js encrypt
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站