简体   繁体   中英

c++, how bit shifting by n works

I'm wondering how bit shifting works. For example, if we do i>>3 , does it shift i to the right three times (ie i=i>>1; i=i>>1; i=i>>1 ) or does it change each bits' positions by three at once (ie x[a+3] for all bit positions)?

This is not specified by the language and hence implementation dependent. The compiler will generally implement the most efficient solution.

How a compiler generates code for a bit shift operation depends on the target architecture and the optimization level of the compiler. Different architectures have different opcodes for shifting.

For example:

#include <stdio.h>

int main(void)
{
    int i = 0xaa;

    i = i >> 3;

    printf("%d\n", i);
}

Look at the different assembly outputs from GNU GCC 7.2 x86_64 with different optimization levels: only for -O0 the compiler uses an opcode for bit shift:

sar DWORD PTR [rbp-4], 3

for all other optimization levels, the compiler stores the value 0x15 directly into edi .

Not let's change the code a little bit:

int main(int argc, char **argv)
{
    int i = argc;

    i = i >> 3;

    printf("%d\n", i);
}

Now suddenly all optimization are using the sar opcode to do calculate the bit shift.

As you can see, there is no definitive answer to that, other than compilers are very clever and will try to use the most efficiant way of doing stuff, and sometimes not doing them is "better". Play with different compilers on the godbolt.org links I provided to see the different ways different compiler versions deal with it. If you change on godbolt.org compiler explorer the language to C++, you can even compile it for different architectures like arm and mips .

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