使用按位或在JavaScript转换为整数 [英] using bitwise OR in javascript to convert to integer
本文介绍了使用按位或在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)
这篇关于使用按位或在JavaScript转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文