buffer
buffer copied to clipboard
Buffer treats decimal numbers mod 100??
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
That's a parseInt() behavior, unrelated to Buffer: parseInt(0x61, 16) === 0x97.
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.
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 ]
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.
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.