The avalanche effect says a small input change should flip about half of a hash's bits. Counting the differing bits measures it.
What to build
For each pair of equal-length hex strings, count the bits that differ.
Requirements
- Each line has two hex strings of the same length, separated by a space (upper or lower case).
- Print
N of M bits differ (P%), where M is 4 × the number of hex digits and P has one decimal place.
Input
One pair per line.
Output
One line per pair.
Constraints
Each string has 1 to 64 hex digits.
Example
Input:
d57ecea9 16edd958
Output:
17 of 32 bits differ (53.1%)
Why it works
XOR of two digits has a 1 bit exactly where they differ, so counting the 1 bits of each digit's XOR and adding them up gives the total distance.
Examples
Example 1 · Input
d57ecea9 16edd958
Expected output
17 of 32 bits differ (53.1%)
Example 2 · Input
00 ff
Expected output
8 of 8 bits differ (100.0%)
Hints
Hint 1
parseInt(ch, 16) turns one hex digit into 0 to 15.
Hint 2
Count bits with a loop: while (x) { count += x & 1; x >>= 1; }
Solution
Show one correct solution (try it yourself first)
let line = prompt();
while (line !== null) {
const [a, b] = line.trim().split(/\s+/);
let diff = 0;
for (let i = 0; i < a.length; i++) {
let x = parseInt(a[i], 16) ^ parseInt(b[i], 16);
while (x) {
diff += x & 1;
x >>= 1;
}
}
const total = a.length * 4;
console.log(`${diff} of ${total} bits differ (${((diff / total) * 100).toFixed(1)}%)`);
line = prompt();
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step