buffer icon indicating copy to clipboard operation
buffer copied to clipboard

Buffer treats decimal numbers mod 100??

Open nanaknihal opened this issue 3 years ago • 5 comments

Running v17.3.0, Buffer.from("abcde") returns <Buffer 61 62 63 64 65> as expected Buffer.from("abcde").map(x=>parseInt(x,16)) returns <Buffer 97 98 99 00 01> This is probably not the intended behavior of Buffer

nanaknihal avatar Aug 02 '22 12:08 nanaknihal

That's a parseInt() behavior, unrelated to Buffer: parseInt(0x61, 16) === 0x97.

vweevers avatar Aug 02 '22 12:08 vweevers

That's a parseInt() behavior, unrelated to Buffer: parseInt(0x61, 16) === 0x97.

That's approximately what parseInt does, which is fine. The problem seems to be from Buffer, not parseInt:

Buffer.from("abcde").map(x=>parseInt(x,16)) returns

<Buffer 97 98 99 00 01> instead of

<Buffer 97 98 99 100 101> or

some other array with 97, 98, 99, 100, 101.

nanaknihal avatar Aug 02 '22 18:08 nanaknihal

The maximum value of a byte is 255. Buffer is a Uint8Array (rather than a Uint8ClampedArray), so values get wrapped.

$ node
> new Uint8Array([255, 256, 257])
Uint8Array(3) [ 255, 0, 1 ]
> new Uint8ClampedArray([255, 256, 257])
Uint8ClampedArray(3) [ 255, 255, 255 ]

vweevers avatar Aug 02 '22 18:08 vweevers

Yes. Although it oddly wraps at 100 instead of 256. I think Buffer is treating the result of parseInt as 0x100 instead of 100.

I don't know the exact interface between Buffer and parseInt; perhaps this is difficult to fix and best remain a "feature" rather than a bug. It is unintuitive but perhaps it's just how Buffers work and there's no way around it.

nanaknihal avatar Aug 02 '22 21:08 nanaknihal

Yes. Although it oddly wraps at 100

A hexadecimal 100. Perhaps that's where the confusion comes from: console.log(buffer) prints a hexadecimal representation of the bytes. Here's an easy way to demonstrate that:

$ node
> Buffer.from('abcde')
<Buffer 61 62 63 64 65>
> Buffer.from('abcde').toString('hex')
'6162636465'

There's no bug here.

vweevers avatar Aug 02 '22 22:08 vweevers