How to rotate a number to the right by N bits using bit operation in C#

1 Answer

0 votes
using System;

class Program
{
    private static int rotate_right(int num, int n) {
        return (num >> n) | (num << (32 - n));
    }
    
    static void Main() {
        int num = 16;
        
        Console.WriteLine(Convert.ToString(num, 2).PadLeft(16, '0'));

        num = rotate_right(num, 2);
        
        Console.WriteLine(Convert.ToString(num, 2).PadLeft(16, '0'));
        
        Console.WriteLine(num);
    }
}




/*
run:

0000000000010000
0000000000000100
4

*/

 



answered Jan 9, 2023 by avibootz
...