简体   繁体   中英

JavaScript Zero Bitwise Left-Shift and Right-Shift Equivalent in Python?

In JavaScript, we can use bitwise left-shift and right-shift operators to truncate a float and round it down to the nearest integer.

Example:

console.log(2.667 << 0); //outputs 2
console.log(2.667 >> 0); //outputs 2

These bitwise operators also do the same thing:

console.log(2.667 | 0); //outputs 2
console.log(0 | 2.667); //outputs 2
console.log(~~2.667); //outputs 2

In Python, however, the same operations return errors.

Is there any equivalent in Python -- using bitwise operators? Or must I use int() and floor division to achieve what I'm looking for?

Bitwise operators don't work on python floats. In fact, JS is the only language where I might expect that to work... Frankly, the fact that they work on JS numbers is probably an artifact of the fact that JS doesn't actually have an integer type...

If you call int on your float and then use the bitwise operators in python everything should work out the same. eg

>>> int(2.667) << 0
2

Of course, if all you are trying to do is to truncate a float, you can just call int on it and all should be right with the world.

just cast the float to an int int(2.667) it will always floor/truncate the float once the float is non negative if you have negative numbers you do want to floor not just truncate use math.floor .

In [7]: int(2.667 )
Out[7]: 2

In [22]: from math import floor

In [23]: int(floor(-2.667 )) # just floor(-2.667 ) using python3
Out[23]: -3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM