FNV-1a squeezes any text into 32 bits. It is a hash-table hash, not a security one, but it shows the fixed size and the spread of a hash.
What to build
Print the FNV-1a hash of each line.
Requirements
- FNV-1a 32-bit: start at 2166136261; for each character, XOR the hash with the character code, then multiply by 16777619 keeping 32 bits (
Math.imul(hash, 16777619) >>> 0). Print it as 8 lower-case hex digits. - Hash each line exactly as read, including spaces.
Input
One or more lines of text.
Output
One 8-digit hash per line.
Constraints
1 to 50 lines of up to 200 characters, character codes 32 to 126.
Example
Input:
a
Pay 500 taka
Output:
e40c292c
d57ecea9
Why it works
XOR mixes each character in and the odd multiplier spreads its effect over the high bits, so every input ends as exactly 32 bits however long it was.
Examples
Example 1 · Input
a Pay 500 taka
Expected output
e40c292c d57ecea9
Example 2 · Input
Pay 501 taka
Expected output
16edd958
Hints
Hint 1
Math.imul multiplies as 32-bit integers; >>> 0 turns the result into an unsigned number.
Hint 2
toString(16).padStart(8, "0") keeps leading zeros.
Solution
Show one correct solution (try it yourself first)
function fnv1a(text) {
let hash = 2166136261;
for (let k = 0; k < text.length; k++) {
hash = hash ^ text.charCodeAt(k);
hash = Math.imul(hash, 16777619) >>> 0;
}
return hash.toString(16).padStart(8, "0");
}
let line = prompt();
while (line !== null) {
console.log(fnv1a(line));
line = prompt();
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step