Search code examples
cbit-manipulationpremature-optimization

which bit-manipulation method is more efficient in C?


Base on the answers i've got, i think this problem is kind of meaningless. Thanks for all your kind replies!

i want to get a binary number with its rightmost j bits set to 1 and others set to be 0. basically, there are two methods. i wanna know which of them is more efficient, or is there a more efficient way than these two?

1. ~(~0 << j)
2. (1 << j) - 1

Solution

  • Not sure if it's the answer you're looking for, but I'll bet it won't make more than a nanosecond of difference. :)

    Or, to put it another way: Don't micro-optimize it unless that one-liner is the bottleneck in your code.

    If you need other forms of fast bit manipulation that might actually be slower, try looking at the compiler intrinsic functions, like _BitScanForward. Those might actually make your bit operations faster, when used correctly (but not in a situation like this).