Question

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.

Était-ce utile?

La solution

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.

Autres conseils

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top