The meaning of this `long` function (two's complement and bit-shifting)

Viewed 36

I have encountered this function:

const LIMIT32 = 2147483648; // The limit at which a 32-bit number switches signs == 2 ^ 31

function long(v) {  
  // Two's complement
  if (v >= LIMIT32) {
    v = -(2 * LIMIT32 - v);
  }

  return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
}

// e.g.
[-3, -2, -1, 0, 1,
 -2147483649,-2147483648,-2147483647,
  2147483647,2147483648,2147483649].forEach(x => 
  console.log(`${x}: ${long(x)}`)
);

I'm wondering generally what this function is doing (why it's returning an array, and what the array elements are).

Then I'm wondering why it takes the v and does what looks like a sign flip and some multiplication.

Finally, the meaning of the bitshift and & operations for each item, why it's as multiples of 8, and why they chose 0xFF.

1 Answers

I'm wondering generally what this function is doing (why it's returning an array, and what the array elements are).

It returns an array of the 4 bytes that make up a int32 value. Why someone wrote the code to do that? I don't know.

Then I'm wondering why it takes the v and does what looks like a sign flip and some multiplication.

Because that's how int32 works: 0x7FFFFFFF + 1 === -0x80000000.

Although it is unnecessary in this code, the bit operations will take care of everything.

Finally, the meaning of the bitshift and & operations for each item, why it's as multiples of 8, and why they chose 0xFF.

Getting the distinct bytes of the int32, each one 8 bit long.

Related