calgorithmbit-manipulationbranchless

Set 8th bit if all lower 7 bits are set without branching


I am trying to set the highest bit in a byte value only when all lower 7 bits are set without introducing branching.

for example, given the following inputs:

input: 0b_0010_1100 -> return same value
input: 0b_0101_0101 -> return same value
input: 0b_0111_1111 -> all bits set except MSB, return 0xff
input: 0b_1010_1100 -> MSB is already set, return same value

This only needs to work for values of 8-bit size.

I tried a few attempts using popcount but that didn't work for all input.


Solution

  • How about:

    return x | ((x+1) & 0x80);