有没有办法在C#中执行循环位移?

Jas*_*n Z 34 c# bit-manipulation

我知道以下是真的

int i = 17; //binary 10001
int j = i << 1; //decimal 34, binary 100010
Run Code Online (Sandbox Code Playgroud)

但是,如果你换得太远,那些位就会掉线.发生这种情况的原因与您正在使用的整数大小有关.

有没有办法执行移位,以便位旋转到另一侧?我正在寻找一个单独的操作,而不是for循环.

Chr*_*org 48

如果您知道类型的大小,您可以执行以下操作:

uint i = 17;
uint j = i << 1 | i >> 31;
Run Code Online (Sandbox Code Playgroud)

...将执行32位值的循环移位.

作为循环移位左移n位的推广,在ab位变量上:

/*some unsigned numeric type*/ input = 17;
var result = input  << n | input  >> (b - n);
Run Code Online (Sandbox Code Playgroud)


@评论,似乎C#确实以不同方式处理高位有符号值.我在这里找到了一些相关信息.我还将示例更改为使用uint.

  • 好吧,无论如何,只有无符号整数才能旋转位. (5认同)
  • @ LasseV.Karlsen:我不一定同意这一点.[`GetHashCode`](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx)返回一个(签名的)`int`,如果你想通过使用均匀分配哈希码它的全部32位(*可以*涉及位旋转),符号并不重要 - 显然会妨碍位旋转. (2认同)
  • 奇怪的是,考虑到“ror”和“rol”都是裸 x86 CPU 指令集的一部分,它甚至需要这么多代码。难道他们不能在 C# 中制作一条“&lt;&lt;&gt;”指令或其他指令吗? (2认同)

jai*_*unt 11

一年前,我将为我的本科毕业论文实施MD4.这是我使用UInt32实现循环位移.

private UInt32 RotateLeft(UInt32 x, Byte n)
{
      return UInt32((x << n) | (x >> (32 - n)));
}
Run Code Online (Sandbox Code Playgroud)


phu*_*clv 5

由于 .NET Core 3.0 及更高版本BitOperations.RotateLeft()BitOperations.RotateRight()因此您可以使用类似的东西

BitOperations.RotateRight(12, 3);
BitOperations.RotateLeft(34L, 5);
Run Code Online (Sandbox Code Playgroud)

在以前的版本中,您可以在 Microsoft.VisualStudio.Utilities 中使用BitRotator.RotateLeft()BitRotator.RotateRight()