Skip to content

Buffer treats decimal numbers mod 100??  #317

Open

Description

@nanaknihal

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

Activity

  1. vweevers commented on Aug 2, 2022

    @vweevers

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

  2. nanaknihal commented on Aug 2, 2022

    @nanaknihal
    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.

  3. vweevers commented on Aug 2, 2022

    @vweevers

    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 ]
    
  4. nanaknihal commented on Aug 2, 2022

    @nanaknihal
    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.

  5. vweevers commented on Aug 2, 2022

    @vweevers

    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions