Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Buffer treats decimal numbers mod 100?? #317

Open
nanaknihal opened this issue Aug 2, 2022 · 5 comments
Open

Buffer treats decimal numbers mod 100?? #317

nanaknihal opened this issue Aug 2, 2022 · 5 comments

Comments

@nanaknihal
Copy link

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

@vweevers
Copy link

vweevers commented Aug 2, 2022

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

@nanaknihal
Copy link
Author

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.

@vweevers
Copy link

vweevers commented Aug 2, 2022

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 ]

@nanaknihal
Copy link
Author

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.

@vweevers
Copy link

vweevers commented Aug 2, 2022

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.

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

No branches or pull requests

2 participants