js-xxhash icon indicating copy to clipboard operation
js-xxhash copied to clipboard

toString(16) method is not a fixed length

Open aliqandil opened this issue 5 years ago • 3 comments

Well it's a pretty self explainetory issue, when the hash has leading zeros, it'll be omitted. And that's something you'll never see in the output hash of any other algorithm, like sha256. Just to make sure, I did check the python implementation of xxh64 and it also keeps the leading zeroes.

For example for XXH64......toString(16) this is the fix I used: if( hash.length < 16 ) hash = '0'.repeat( 16 - hash.length ) + hash

Hope it helps, and thanks :)

aliqandil avatar May 17 '19 00:05 aliqandil

I agree. This is confusing! 2 hours of debugging ^^

Example which demonstrates this case:

var XXH = require("xxhashjs")

var H = XXH.h64( 0xABCD )   // seed = 0xABCD

for(let i = 0; i < 100; ++i) {
    var h = H.update( '' + i ).digest().toString(16)
    if(h.length < 16) console.log(h, h.length)
}

Thank you very much for your fix @aliqandil ;)

folkvir avatar Jun 19 '19 17:06 folkvir

Sorry to hear that you wasted your time on this. I welcome pull request btw, as I have little time to maintain my hobby projects atm!

pierrec avatar Jun 19 '19 18:06 pierrec

Hexadecimal numbers below 16 can be represented by a single character, potentially leading to uneven string lengths. Maybe we could add a function to replace toString, which internally runs toString and then applies either of the following methods:

.padStart(16, '0')

Or

if (result.length % 2 !== 0) {
    result = '0' + result;
}
return result;

It checks whether the resulting hexadecimal string's length is odd, which means it would only have one character if the most significant digit of the original number was less than 16.

Overwriting toString may cause issues for people not aware of the change. This approach, while functional, may not be the optimal solution, but it's a consideration worth exploring

Levii22 avatar May 05 '24 14:05 Levii22