Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# bitwise rotate left and rotate right

What is the C# equivalent (.NET 2.0) of _rotl and _rotr from C++?

like image 818
Prithis Avatar asked May 01 '09 16:05

Prithis


2 Answers

Is this what you are trying to do?

Jon Skeet answered this in another site

Basically what you want is

(for left)

(original << bits) | (original >> (32 - bits)) 

or

(for right)

(original >> bits) | (original << (32 - bits)) 

Also, as Mehrdad has already suggested, this only works for uint, which is the example that Jon gives as well.

like image 111
Joseph Avatar answered Oct 02 '22 01:10

Joseph


There's no built-in language feature for bit rotation in C#, but these extension methods should do the job:

public static uint RotateLeft(this uint value, int count) {     return (value << count) | (value >> (32 - count)) }  public static uint RotateRight(this uint value, int count) {     return (value >> count) | (value << (32 - count)) } 

Note: As Mehrdad points out, right-shift (>>) for signed integers is a peculiarity: it fills the MSBs with sign bit rather than 0 as it does for unsigned numbers. I've now changed the methods to take and return uint (unsigned 32-bit integer) instead - this is also in greater accordance with the C++ rotl and rotr functions. If you want to rotate integers, just case them before passing, and again cast the return value, of course.

Example usage:

int foo1 = 8.RotateRight(3); // foo1 = 1 int foo2 = int.MinValue.RotateLeft(3); // foo2 = 4 

(Note that int.MinValue is 111111111111111111111111 - 32 1s in binary.)

like image 33
Noldorin Avatar answered Oct 02 '22 02:10

Noldorin