Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Circular shift using bitwise operations

Tags:

java

I am wondering how to implement a circular right shift by k of the bitstring represented by the int bits.

public int rtCircShift(int bits, int k) {     return bits >> k; } 

All this code does is return 0, how can I make it a circular shift?

like image 623
john Avatar asked Apr 30 '11 19:04

john


People also ask

What is this >>> bitwise operator in Java?

This operator is a binary operator, denoted by '|'. It returns bit by bit OR of input values, i.e., if either of the bits is 1, it gives 1, else it shows 0. Example: a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise OR Operation of 5 and 7 0101 | 0111 ________ 0111 = 7 (In decimal)


1 Answers

You mean you want the bits rotated off the right-hand side to appear on the left?

return Integer.rotateRight(bits, k); 

Example:

int n = 0x55005500; // Binary 01010101000000000101010100000000 int k = 13; System.err.printf("%08x%n", Integer.rotateRight(n, k)); 

output:

a802a802 // Binary 10101000000000101010100000000010 
like image 54
finnw Avatar answered Oct 01 '22 18:10

finnw