简体   繁体   English

C ++,n位移位的工作原理

[英]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)? 例如,如果我们执行i>>3 ,它会将i右移三次(即i=i>>1; i=i>>1; i=i>>1 )还是改变每个位的值?一次增加三个位置(即所有位的x[a+3] )?

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: 查看具有不同优化级别的GNU GCC 7.2 x86_64的不同汇编输出 :仅对于-O0 ,编译器使用操作码进行移位:

sar DWORD PTR [rbp-4], 3

for all other optimization levels, the compiler stores the value 0x15 directly into edi . 对于所有其他优化级别,编译器将值0x15直接存储到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. 现在突然之间所有优化都使用sar操作码来计算位移。

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. 在我提供的godbolt.org链接上使用不同的编译器,以了解不同编译器版本处理它的不同方式。 If you change on godbolt.org compiler explorer the language to C++, you can even compile it for different architectures like arm and mips . 如果您在godbolt.org编译器资源管理器上更改了C ++语言,则甚至可以针对arm和mips之类的不同体系结构对其进行编译。

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

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