2

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?

1
  • 1
    There are bitwise operators but you can't bitwise shift a float like that... Javascript has a lot of non-standard behaviour. What you want is round, floor, or int, depending on your context. Commented Jan 20, 2015 at 17:05

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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. e.g.

>>> 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.