Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't my JavaScript toHexString function work properly with Uint8Array?

Tags:

javascript

This is my toHexString function:

function toHexString(bytes) {
    return bytes.map(function (byte) {
        return ("00" + (byte & 0xFF).toString(16)).slice(-2)
    }).join('')
}

And this is what I have done in Chrome Console:

> var bitmapArray = new Uint8Array(buffer);

undefined

> toHexString(bitmapArray.subarray(0,3))

"2100"

> bitmapArray.subarray(0,3)

[33, 29, 31]

> toHexString([33,29,31])

"211d1f"

It seems that toHexString function cannot work properly. What's the problem?

like image 608
t123yh Avatar asked Aug 25 '26 10:08

t123yh


1 Answers

The map method of typed arrays returns another typed array of the same type. This will cast your strings "21", "1d", "1f" to bytes, by interpreting them as decimal integers - which the latter two are not, so NaN becomes 0 and you end up with the Uint8Array([21, 0, 0]).

To fix this, use a normal Array that can contain strings:

toHexString(Array.from(bitmapArray.subarray(0,3)))

or probably even better

function toHexString(bytes) {
    return Array.from(bytes, byte =>
        ("00" + (byte & 0xFF).toString(16)).slice(-2)
    ).join('');
}
like image 72
Bergi Avatar answered Aug 27 '26 07:08

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!