Search code examples
javascriptpythonbit-manipulationroundingfloor

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?


Solution

  • 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