Search code examples
javascriptnode.jshashhash-functionadler32

Why does my Adler-32 Hash Function miss a zero every time?


I'm trying to code the Adler-32 Hash Function from scratch just to have some fun, I've gotten it completed except for the fact that every time I hash a string it's always missing the zero in the front. I've gone through the formula and Adler-32 descriptions dozens of times and I can't figure out why my code is producing it. Code Below.

function toAdler32(str) {

    if (typeof str != "string") throw new Error('HashUtil: Data passed to Hash function was not of type String.');

    let A16 = 1;
    let B16 = 0;

    for (let i = 0; i < str.length; i++) {

        A16 += (str.charCodeAt(i)) % 65521;
        B16 += A16 % 65521;
    }

    return ((B16 << 16) | A16).toString(16);
}

console.log(toAdler32('test'));

// Returns `45d01c1` when it should return `045d01c1`.

Solution

  • You need to pad it with 0's - it's dropping the leading 0 because the leading 0 is meaningless in a number, regardless of base 10 or base 16...

    If you have 100 cards, you don't say you have 0100 cards, because you don't need the leading 0.

    If you want the string to be a certain length, zero-pad it:

    How can I pad a value with leading zeros?