简体   繁体   English

(B&(1 &lt; <i)) VS ((b > &gt; i)和1)C ++

[英](b&(1<<i)) VS ((b >> i) & 1) C++

It is often necessary to represent a datatype as a sequence of bits and fetch them inside a loop for the entire length. 通常有必要将数据类型表示为一系列位,并在整个长度的循环内读取它们。 Although I find ((b >> i) & 1) more intuitive, recently I saw a book use (b&(1<<i)) . 尽管我发现((b >> i) & 1)更直观,但是最近我看到了一本书的使用(b&(1<<i)) Is any one of them more favorable or more efficient and if one of them is, why? 它们中的任何一个是更有利还是更有效?如果其中之一是,为什么?

Assuming you use this to test a bit (so the difference in result is irrelevant), it depends on the context and on what the compiler does with it and other factors. 假设您使用此工具进行测试(因此结果的差异无关紧要),则取决于上下文,编译器对其进行的操作以及其他因素。

For example, when compiled with GCC 7.3 for modern x86, they are exactly the same , both can compile to this sequence: 例如,当使用GCC 7.3针对现代x86进行编译时,它们完全相同 ,两者都可以编译为以下顺序:

sarx eax, edi, esi
and eax, 1

And when using the result to actually make a decision (instead of materialising the boolean) the code can still be the same. 而且,当使用结果实际做出决定(而不是实现布尔值)时,代码仍然可以相同。 Obviously if the code is going to be the same, there can be no difference in efficiency. 显然,如果代码将相同,则效率不会有差异。 Clang likes to use bt and setc (or using the flag in a cmov or control flow when appropriate), but also does the same thing for both snippets. Clang喜欢使用btsetc (或者在适当的时候在cmov或控制流中使用该标志),但是对两个代码片段也做同样的事情。 MSVC does compile the snippets in different ways, and maybe "prefers" the 1 << i formulation in some sense. MSVC确实以不同的方式来编译代码片段,并且在某种意义上也许“更喜欢” 1 << i公式。

Implementing b & (1 << i) literally (which I did not observe any compiler actually do) takes an extra instruction to load a constant 1 into a register, though that does not necessarily mean it would take extra time (though it can): creating the 1 is independent of everything else so it can potentially execute ahead of everything else, and then the shift is independent of b so it can execute after i is ready but before b is. 从字面上实现b & (1 << i) (我没有观察到任何编译器实际上执行过)需要一条额外的指令将常量1加载到寄存器中,尽管这并不一定意味着会花费额外的时间(尽管可以) :创建1独立于其他所有东西,因此它可能比其他所有东西先执行,然后移位独立于b因此它可以在i准备好之后但在b之前执行。

Which is more favorable? 哪个更有利?

Depends on what data you need. 取决于您需要什么数据。

((b >> i) & 1) gives you a 1 or 0.

(b & (1 << i)) gives you a 0 or 2^i.

Which is more efficient? 哪个更有效?

Difference in efficiency is negligible between them. 它们之间的效率差异可以忽略不计。 Plus, the difference differs in different architecture and code compiled. 另外,区别在于不同的体系结构和编译的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM