如果所有低7位都设置而没有分支,则设置第8位
我试图仅在设置所有低 7 位而不引入分支时才设置字节值中的最高位。
例如,给定以下输入:
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
这仅需要适用于 8 位大小的值。
我尝试了几次尝试,popcount但这不适用于所有输入。
回答
怎么样:
return x | ((x+1) & 0x80);
- Or `return x | (((x & 0x7F)+1) & 0x80);` if other bits can be set as well.
- @Lundin: If MSB is already set, then `x | (anything & MSB)` is guaranteed to do absolutely nothing regardless of what `anything` is.