3

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?

1 Answer 1

3

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('');
}
Sign up to request clarification or add additional context in comments.

3 Comments

Works like a charm. Thanks!
How could I do that on elder browsers such as IE? It seems that IE doesn't support Array.from. Neither does Safari.
You can easily polyfill Array.from, but I doubt older browsers would support typed arrays anyway (and certainly not typed arrays with a map method).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.