简体   繁体   中英

(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)) . 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:

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. MSVC does compile the snippets in different ways, and maybe "prefers" the 1 << i formulation in some sense.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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