I wonder, is it possible to achieve similar using bit operations:

if a > maximum: a = maximum

Where 'maximum' can be a random number?

Have many similar lines in my current code. Of course could have used:

def foo(a, max=512): return a if a<max else max

Just curious if there's a more elegant and efficient way.

有帮助吗?

解决方案

There's no need to define your own function for this, min and max are already built-in:

a = min(maximum, a)

As per Raymond's answer, it is also possible to use bit operations:

a = maximum ^ ((a ^ maximum) & -(a < maximum))

But in the vast majority of cases, the performance benefit isn't really worth making the code very hard to understand. Also, this only works for integers, whereas the min function can be used for all comparable types.

其他提示

Using max and min would make for clear code.

That being said, it is possible to use bit-twiddling: http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top