Given an integer x, right-propagate the rightmost set bit: set all bits to the right of the rightmost 1 (inclusive) to 1, leaving higher-order bits unchanged. Formally return x | (x - 1).
Subtracting 1 from x clears the rightmost 1 bit and sets all lower bits to 1 (they were zeros). OR-ing with the original x therefore preserves higher-order bits and turns all lower bits (including the rightmost 1) into 1.
Locate the index pos of the rightmost set bit and construct a mask of pos lower bits set to 1 ((1 << pos) - 1). OR this mask with x to turn on all lower bits.
⏰ Time complexity: O(w) where w is the word size (number of bits) due to scanning bits; in practice O(1) for fixed-width integers.
🧺 Space complexity: O(1).
Notes
The canonical one-line trick is x | (x - 1) (Method 1). Be aware that when x == 0 this expression produces all 1 bits due to unsigned underflow; choose guarded behavior if that is undesirable.
Reference: original bit-hacks collection in source_links.