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

1 Answer

0 votes
function rotate_right(num, n) {
    return (num >> n) | (num << (32 - n));
}

let num = 16;

console.log(("00000000" + num.toString(2)).substr(-8));
        
num = rotate_right(num, 2);

console.log(("00000000" + num.toString(2)).substr(-8));

console.log(num);





/*
run:

"00010000"
"00000100"
4

*/

 



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