I want to be able to set or clear (multiple) bits of a uintX_t t
.
i
is a runtime variable (uintX_t
).
b
is a runtime variable (uintX_t
) which is constrained to be 0
or 1
.
mask
is a compile-time constant.
Is there a better way than:
i = b ? (i | mask) : (i & ~mask)
I'm looking to avoid branching, if that's possible. Target is ARM, if it matters.
Exploiting the fact that -1u
is the value with all bits set:
i = (i & ~mask) | (mask & -b);
or
i ^= (i ^ -b) & mask;
The second approach reduces the number of operations and code size. The first approach may still be faster on a superscalar architecture because some operations can be executed in parallel.
Another alternative: Always set bits to 0 (left part) and optionally set bits to 1 (right part).
i = (i & ~mask) | (mask * b);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With