bit manipulation - Bitwise operations in C# -
is there shorter , better-looking alternative to
(b == 0) ? 0 : 1;
in terms of bitwise operations?
also, correct sign (-1, 0 or 1) of given integer a
using
(a > 0) ? 1 : (a >> 32);
are there shorter (but not slower) ways?
personally i'd stick first option "equal 0 or not" option.
for sign of integer, i'd use math.sign , assume jit compiler going inline - testing assumption benchmarks if turns out potential bottleneck.
think readability above - first piece of code blindingly obvious. second isn't. i'm not convinced second piece of code works... thought right-shifts masked bottom 5 bits, assuming int32
(int
).
edit: checked, , indeed current second piece of code equivalent to:
int y = x > 0 ? 1 : x;
the shift doesn't end in compiled code.
take object lesson caring more micro-optimization readability. it's easier make code work if it's easy understand. if code gives wrong result, don't care how runs.
Comments
Post a Comment