在 javascript 中设置第 31 位是否正确?
Is it correct to set bit 31 in javascript?
当我尝试设置 31 位时 0 | 1 << 31
我得到以下结果:
console.log(0 | 1 << 31); // -2147483648
实际上是:
console.log((-2147483648).toString(2)) // -10000000000000000000000000000000
设置 31 位是否正确,还是我应该限制为 30
以防止出现负值?
大多数按位运算被指定为将它们的操作数转换为有符号 32 位整数。使用第 31 位是完全正确的,但是,是的,你会得到负值。通常不管你是否在进行按位运算都没有关系,因为你(应该)关心的只是位模式,而不是数字的十进制值。
如果你做想要返回一个正值,你可以用>>> 0
将它转换回来,因为>>>
被指定将其操作数转换为无符号 32 位整数。
console.log((0 | 1 << 31) >>> 0);
参考ECMA5
,按位运算符和移位运算符对32位整数进行运算,因此在这种情况下,最大安全整数为2^31-1,即2147483647。
这是一个 explanation。
The <<
operator is defined as working on signed 32-bit
integers (converted from the native Number storage of double-precision float). So 1<<31
must result in a negative number.
The only JavaScript operator that works using unsigned 32-bit
integers is >>>
. You can exploit this to convert a signed-integer-in-Number you've been working on with the other bitwise operators to an unsigned-integer-in-Number:
(1<<31)>>>0
当我尝试设置 31 位时 0 | 1 << 31
我得到以下结果:
console.log(0 | 1 << 31); // -2147483648
实际上是:
console.log((-2147483648).toString(2)) // -10000000000000000000000000000000
设置 31 位是否正确,还是我应该限制为 30
以防止出现负值?
大多数按位运算被指定为将它们的操作数转换为有符号 32 位整数。使用第 31 位是完全正确的,但是,是的,你会得到负值。通常不管你是否在进行按位运算都没有关系,因为你(应该)关心的只是位模式,而不是数字的十进制值。
如果你做想要返回一个正值,你可以用>>> 0
将它转换回来,因为>>>
被指定将其操作数转换为无符号 32 位整数。
console.log((0 | 1 << 31) >>> 0);
参考ECMA5
,按位运算符和移位运算符对32位整数进行运算,因此在这种情况下,最大安全整数为2^31-1,即2147483647。
这是一个 explanation。
The
<<
operator is defined as working on signed32-bit
integers (converted from the native Number storage of double-precision float). So1<<31
must result in a negative number.The only JavaScript operator that works using unsigned
32-bit
integers is>>>
. You can exploit this to convert a signed-integer-in-Number you've been working on with the other bitwise operators to an unsigned-integer-in-Number:
(1<<31)>>>0