这个 long 函数的含义(二进制补码和位移位)
The meaning of this `long` function (two's complement and bit-shifting)
我遇到过这个功能:
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)}`)
);
我一般想知道这个函数在做什么(为什么它返回一个数组,以及数组元素是什么)。
然后我想知道为什么它采用 v
并执行看起来像符号翻转和一些乘法的操作。
最后是每一项的bitshift和&
操作的意义,为什么是8的倍数,为什么选择0xFF
。
I'm wondering generally what this function is doing (why it's returning an array, and what the array elements are).
它returns 组成 int32 值的 4 个字节的数组。为什么有人编写代码来做到这一点?我不知道。
Then I'm wondering why it takes the v and does what looks like a sign flip and some multiplication.
因为这就是 int32 的工作原理:0x7FFFFFFF + 1 === -0x80000000
。
虽然在这段代码中没有必要,但位操作会搞定一切。
Finally, the meaning of the bitshift and & operations for each item, why it's as multiples of 8, and why they chose 0xFF.
获取 int32 的不同字节,每个字节长 8 位。
我遇到过这个功能:
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)}`)
);
我一般想知道这个函数在做什么(为什么它返回一个数组,以及数组元素是什么)。
然后我想知道为什么它采用 v
并执行看起来像符号翻转和一些乘法的操作。
最后是每一项的bitshift和&
操作的意义,为什么是8的倍数,为什么选择0xFF
。
I'm wondering generally what this function is doing (why it's returning an array, and what the array elements are).
它returns 组成 int32 值的 4 个字节的数组。为什么有人编写代码来做到这一点?我不知道。
Then I'm wondering why it takes the v and does what looks like a sign flip and some multiplication.
因为这就是 int32 的工作原理:0x7FFFFFFF + 1 === -0x80000000
。
虽然在这段代码中没有必要,但位操作会搞定一切。
Finally, the meaning of the bitshift and & operations for each item, why it's as multiples of 8, and why they chose 0xFF.
获取 int32 的不同字节,每个字节长 8 位。