【问题标题】:Why is this statement with bitwise operators the same as this if statement? [duplicate]为什么这个按位运算符的语句与这个 if 语句相同? [复制]
【发布时间】:2014-12-28 06:43:39
【问题描述】:

我正在阅读这个问题 Why is it faster to process a sorted array than an unsorted array? 和提供的最佳答案 神秘的。答案很好地解释了正在发生的事情和原因,并且还这么说:

那么有什么办法呢?

如果编译器无法将分支优化为条件 移动,如果您愿意牺牲,可以尝试一些技巧 性能的可读性。

替换:

 if (data[c] >= 128)
     sum += data[c];

与:

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

这消除了分支并用一些位替换它 操作。

这段代码到底在做什么,为什么它是等价的?

【问题讨论】:

    标签: c if-statement bitwise-operators branch-prediction


    【解决方案1】:

    它首先将比较转换为 128 的减法。

    然后结果的符号(减法是否低于 128)被扩展为全零或全一,这是 anded 到要添加的值,如果减法的结果为负,则将其归零。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-09
      • 2014-01-16
      • 1970-01-01
      • 2020-07-28
      • 2017-01-26
      • 2019-12-11
      • 2011-12-03
      • 1970-01-01
      相关资源
      最近更新 更多