Rotate bits of a number

来源:互联网 发布:java视频教程免费下载 编辑:程序博客网 时间:2024/05/24 02:16

reference: 

http://www.geeksforgeeks.org/rotate-bits-of-an-integer/


Problem Definition:

Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end.

In left rotation, the bits that fall off at left end are put back at right end.

In right rotation, the bits that fall off at right end are put back at left end.


Solution:

Do the navie shift first, and then add the missing information to it again.


Code:

/*Function to left rotate n by d bits*/int leftRotate(int n, unsigned int d){   /* In n<<d, last d bits are 0. To put first 3 bits of n at      last, do bitwise or of n<<d with n >>(INT_BITS - d) */   return (n << d)|(n >> (INT_BITS - d));} /*Function to right rotate n by d bits*/int rightRotate(int n, unsigned int d){   /* In n>>d, first d bits are 0. To put last 3 bits of at      first, do bitwise or of n>>d with n <<(INT_BITS - d) */   return (n >> d)|(n << (INT_BITS - d));}