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.

Example:
Let n is stored using 8 bits. Left rotation of n = 11100101 by 3 makes n = 00101111 (Left shifted by 3 and first 3 bits are put back in last ). If n is stored using 16 bits or 32 bits then left rotation of n (000…11100101) becomes 00..0011100101000.
Right rotation of n = 11100101 by 3 makes n = 10111100 (Right shifted by 3 and last 3 bits are put back in first ) if n is stored using 8 bits. If n is stored using 16 bits or 32 bits then right rotation of n (000…11100101) by 3 becomes 101000..0011100.

[pastacode lang=”c” manual=”%23include%3Cstdio.h%3E%0A%23define%20INT_BITS%2032%0A%20%0A%2F*Function%20to%20left%20rotate%20n%20by%20d%20bits*%2F%0Aint%20leftRotate(int%20n%2C%20unsigned%20int%20d)%0A%7B%0A%20%20%20%2F*%20In%20n%3C%3Cd%2C%20last%20d%20bits%20are%200.%20To%20put%20first%203%20bits%20of%20n%20at%20%0A%20%20%20%20%20last%2C%20do%20bitwise%20or%20of%20n%3C%3Cd%20with%20n%20%3E%3E(INT_BITS%20-%20d)%20*%2F%0A%20%20%20return%20(n%20%3C%3C%20d)%7C(n%20%3E%3E%20(INT_BITS%20-%20d))%3B%0A%7D%0A%20%0A%2F*Function%20to%20right%20rotate%20n%20by%20d%20bits*%2F%0Aint%20rightRotate(int%20n%2C%20unsigned%20int%20d)%0A%7B%0A%20%20%20%2F*%20In%20n%3E%3Ed%2C%20first%20d%20bits%20are%200.%20To%20put%20last%203%20bits%20of%20at%20%0A%20%20%20%20%20first%2C%20do%20bitwise%20or%20of%20n%3E%3Ed%20with%20n%20%3C%3C(INT_BITS%20-%20d)%20*%2F%0A%20%20%20return%20(n%20%3E%3E%20d)%7C(n%20%3C%3C%20(INT_BITS%20-%20d))%3B%0A%7D%0A%20%0A%2F*%20Driver%20program%20to%20test%20above%20functions%20*%2F%0Aint%20main()%0A%7B%0A%20%20int%20n%20%3D%2016%3B%0A%20%20int%20d%20%3D%202%3B%0A%20%20printf(%22Left%20Rotation%20of%20%25d%20by%20%25d%20is%20%22%2C%20n%2C%20d)%3B%0A%20%20printf(%22%25d%22%2C%20leftRotate(n%2C%20d))%3B%0A%20%20printf(%22%5CnRight%20Rotation%20of%20%25d%20by%20%25d%20is%20%22%2C%20n%2C%20d)%3B%0A%20%20printf(%22%25d%22%2C%20rightRotate(n%2C%20d))%3B%0A%20%20getchar()%3B%0A%7D%20″ message=”C programming” highlight=”” provider=”manual”/] [ad type=”banner”]