使用按位或在JavaScript转换为整数
问题描述:
我们可以做以下转换:
var a = "129.13"|0, // becomes 129
var b = 11.12|0; // becomes 11
var c = "112"|0; // becomes 112
这似乎工作,但不知道这是一个标准的JS功能。没有任何一个有任何想法,如果这是可以放心使用的字符串和小数转换为整数?
This seem to work but not sure if this is a standard JS feature. Does any one have any idea if this is safe to use for converting strings and decimals to integers ?
答
是的,这是标准的行为。位运算符只对整数操作,所以他们转换他们给32位有符号整数,任何数字。
Yes, it is standard behavior. Bitwise operators only operate on integers, so they convert whatever number they're give to signed 32 bit integer.
这意味着,最大射程是32位有符号整数减1,这是 2147483647
。
This means that the max range is that of signed 32 bit integer minus 1, which is 2147483647
.
(Math.pow(2, 32) / 2 - 1)|0; // 2147483647
(Math.pow(2, 32) / 2)|0; // -2147483648 (wrong result)