Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

string - using bitwise OR in javascript to convert to integer

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...