chrisdew chrisdew - 22 days ago 5
C Question

Optimising "i = b ? (i | mask) : (i & ~mask)"

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.

Answer

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.