Fred
Fred

Reputation: 1031

16 bit barrel shift in Java

I'm trying to do a rotate right (barrel shift) on an int in Java, e.g.

Input:  0000 0000 0110 1001
Output: 1000 0000 0011 0100

I know I can do a right shift (>>), however I can't work out how to combine this to create a rotate (I'm pretty sure it's possible!).

I think there is a method in java.lang.Math but I'm looking to work out how to use shifts only.

Any ideas?

Upvotes: 0

Views: 1277

Answers (2)

Mat
Mat

Reputation: 206727

int rotated_by_one = ((value & 1)<<15) | (value >> 1)

Upvotes: 0

dty
dty

Reputation: 18998

I'm not sure there's a single operation for this. But something like:

int x = (x >> 1) | (x << 31)  // or 15 if you really did mean 16-bit

would do the trick.

Upvotes: 4

Related Questions