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

I want to be able to set or clear (multiple) bits uintX_t t.

iis the runtime variable ( uintX_t). bis a runtime variable ( uintX_t) that is limited by 0or 1.

mask - constant compilation time.

Is there a better way:

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

I want to avoid branching if possible. The goal is ARM, if that matters.

+4
source share
4 answers

Another alternative: always set the bits to 0 (left side) and arbitrarily set the bits to 1 (right side).

i = (i & ~mask) | (mask * b);
+5
source

, -1u - :

i = (i & ~mask) | (mask & -b);

i ^= (i ^ -b) & mask;

. , .

+6

, , b:

i = (i | (mask * b)) & (~mask | (mask * b));
+5

- - , .

, . , ~ . ( ?: , .)

, , :

uintx_t i = ... ;
uintx_t b = ... ;  // 1 or 0

i &= (uintx_t)~mask;   // always clear the bit
i |= mask * b;         // if b is 1, set the bit, otherwise OR with 0
+1
source

Source: https://habr.com/ru/post/1660924/


All Articles