How to rotate a number to the right by N bits using bit operation in Node.js

1 Answer

0 votes
function rotate_right(num, n) {
    return (num >> n) | (num << (32 - n));
}
 
let num = 64;
 
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:
 
01000000
00010000
16

*/

 



answered Jan 12, 2023 by avibootz
...