理解移位运算符 [英] Understanding The shift operators

查看:102
本文介绍了理解移位运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看一些代码,将无符号整数移位32次,但发现很难理解shift运算符与OR运算符的结合使用。

I'm looking over some code that shifts an unsigned integer 32 times but finding it difficult to understand the use of the shift operators in combination with the OR operator.

作为一个例子,如果变量设置为:

Just as an example what would be the outcome if the variables were set to:

_arg1 = 1
_arg2 = 20

((_arg1 << _arg2) | (_arg1 >> (32 - _arg2)))



如果有更简单的变量值来解释这一点,

If there are easier values for the variables to explain this feel free to change them to better suit your needs.

提前感谢。

推荐答案

<<和>>是移位运算符,它们通过arg2位置移动变量的位...

<< and >> are shift operators, that move the bits of the variable by arg2 positions...

所以如果你有:

11001010 << 2

您将把整个位串两个移动到左边。这实际上将前两个(形成左)位从变量中推出,并且从右侧推入一些0.因此:

you would move the entire bitstring two to the left. This actually pushes the first two (form the left) bits out of the variable, and from the right side some 0's are pushed in. So:

11001010 < 2 = 00101000

11001010 << 2 = 00101000

在您的问题中,您正在轮流轮班。

In your question, you are making a rotate shift.

让我们假设arg1 = 11001010 (二进制)和arg2 = 2,并且当我们使用8位整数时,我们用32替换32.

so lets assume arg1 = 11001010 (in binary) and arg2 = 2, and as we use a 8bit integer, we replace the 32 by an 8.

((11001010 << 2) | (11001010 >> (8 - 2)))
= (00101000 | 00000011)

现在|将两个位串连接到一个字符串,因此如果在一个字符串中设置位,则现在也将在结果中设置:

And now the | connects the two bitstrings to one, so if a bit is set in one string, it will now be also set in the result:

(00101000 | 00000011) == 00101011

那么你的代码实际上是什么?它被称为圆形或旋转移位...它的一侧推出的位,它实际上从另一侧推进。所以你可以旋转bitpattern周围,而不是只是将一边移动到没有,并在另一边添加零。

So what is your piece of code actually doing? It is called a circular or rotate shift... The bits it pushes out on one side, it actually pushes in from the other side. So you can rotate the bitpattern around, instead of just shifting one side into nothing and adding zeros on the other side.

这篇关于理解移位运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆