Skip to content
This repository has been archived by the owner on Sep 9, 2024. It is now read-only.

toString(16) method is not a fixed length #21

Open
aliqandil opened this issue May 17, 2019 · 3 comments
Open

toString(16) method is not a fixed length #21

aliqandil opened this issue May 17, 2019 · 3 comments

Comments

@aliqandil
Copy link

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 :)

@folkvir
Copy link

folkvir commented Jun 19, 2019

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 ;)

@pierrec
Copy link
Owner

pierrec commented Jun 19, 2019

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!

@Levii22
Copy link

Levii22 commented May 5, 2024

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants