Reputation: 4085
In C++, is it possible to achieve the following with a bitwise trick?
(i == 0) ? 1 : i
Assume that i
is an unsigned 32-bit integer.
EDIT: This is out of curiosity. The goal is not to optimize and clearly not to improve readability.
Upvotes: 2
Views: 255
Reputation: 61900
Until I see real results that say otherwise, I believe your code is much clearer and just as fast, but either of these accomplish the same thing without the conditional:
i + !i
Or
i | !i
If i
is 0, !i
is 1. Combining 0 with 1 through addition or bitwise OR always gives 1. If i
is non-zero, !i
is 0. Combining a non-zero value with 0 through addition or bitwise OR always gives that value. Thus, the result is 1 if i
is 0 and i
if not.
Again, I will be surprised if either of these actually turn out to be better for the compiler.
Upvotes: 8
Reputation: 726479
On computers with two's complement representation of negative numbers, you can use this formula:
(!(n & -2)) | n
Explanation: Bit pattern for -2 has ones in all bit positions except the least significant one. Therefore, the expression n & -2
will be zero only when n
is equal to zero or one. The !
will make one from zero and zero from any other number. Hence, zero or one will be OR-ed with one, while any other number will remain intact.
Upvotes: 4