Bit manipulation to avoid branch mispredict

I came across another question on this site explaining about branch misprediction. In the answer, a given solution was to replace the if statement(branch), as below

const unsigned arraySize = 32768;
int data[arraySize];

for(int i = 0; i < arraySize; ++i)
    if (data[c] >= 128) // <- to be replaced
        sum += data[c];

with bitwise operators.

int t = (data[c] - 128) >> 31;
sum += ~t & data[c];

So for values greater or equal to 128 in the data array, t would be 0. So ~t would be equal to 111...1, so bitwise-AND with data[c] would preserve the value. However, when the value is less than 128 in the data array, wouldn't t be equal to 1? So ~t would be 111...0, but shouldn't we bitwise-AND 000...0 with data[c] in order to not add?

链接地址: http://www.djcxy.com/p/6204.html

上一篇: 嵌入与对象

下一篇: 位操作以避免分支错误预测