using bitwise OR in javascript to convert to integer

大城市里の小女人 提交于 2019-12-01 10:38:26

问题


we can do the following to convert:

var a = "129.13"|0,  // becomes 129

var b = 11.12|0; // becomes 11

var c = "112"|0; // becomes 112

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 ?


回答1:


Yes, it is standard behavior. Bitwise operators only operate on integers, so they convert whatever number they're give to signed 32 bit integer.

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)


来源:https://stackoverflow.com/questions/12695504/using-bitwise-or-in-javascript-to-convert-to-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!