[ACCEPTED]-Is there a way to perform a circular bit shift in C#?-bit-manipulation

Accepted answer
Score: 53

If you know the size of type, you could 4 do something like:

uint i = 17;
uint j = i << 1 | i >> 31;

... which would perform 3 a circular shift of a 32 bit value.

As a 2 generalization to circular shift left n 1 bits, on a b bit variable:

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


@The comment, it appears that C# does treat the high bit of signed values differently. I found some info on this here. I also changed the example to use a uint.
Score: 12

One year ago I've to implement MD4 for my 2 undergraduate thesis. Here it is my implementation 1 of circular bit shift using a UInt32.

private UInt32 RotateLeft(UInt32 x, Byte n)
{
      return UInt32((x << n) | (x >> (32 - n)));
}
Score: 6

Sincce .NET Core 3.0 and up there's BitOperations.RotateLeft() and 2 BitOperations.RotateRight() so you can just use something like

BitOperations.RotateRight(12, 3);
BitOperations.RotateLeft(34L, 5);

In previous 1 versions you can use BitRotator.RotateLeft() and BitRotator.RotateRight() in Microsoft.VisualStudio.Utilities

Score: 4

Just as reference on how to do it, these 3 two functions work perfectly for rotating 2 the bits of 1/2word:

static public uint ShiftRight(uint z_value, int z_shift)
{
    return ((z_value >> z_shift) | (z_value << (16 - z_shift))) & 0x0000FFFF;
}

static public uint ShiftLeft(uint z_value, int z_shift)
{
    return ((z_value << z_shift) | (z_value >> (16 - z_shift))) & 0x0000FFFF;
}

It would be easy to 1 extend it for any given size.

Score: 1

The extension methods for rotating bits 1 of a uint (32 bits):

public static uint ROR(this uint x, int nbitsShift)
    => (x >> nbitsShift) | (x << (32 - nbitsShift));

public static uint ROL(this uint x, int nbitsShift)
    => (x << nbitsShift) | (x >> (32 - nbitsShift));

More Related questions