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

1 Answer

0 votes
public class MyClass {
    private static int rotate_right(int num, int n) {
	    return (num >> n) | (num << (32 - n));
    }
    
    public static void main(String args[]) {
        int num = 16;

        System.out.println(String.format("%16s", Integer.toBinaryString(num)).replaceAll(" ", "0"));
        
	    num = rotate_right(num, 2);

	    System.out.println(String.format("%16s", Integer.toBinaryString(num)).replaceAll(" ", "0"));
	    
	    System.out.println(num);
    }
}





/*
run:

0000000000010000
0000000000000100
4

*/

 



answered Jan 9, 2023 by avibootz
edited Jan 9, 2023 by avibootz
...