Skip to the content of the web site.

Project Y.1: Bit rotations

The bit-shift operators loses extra ones that are shifted beyond the size of the type. A rotation moves those bits to the other side.

Value00100010101011101001111011110110
Shifted left by 2111011110110000000000000000000000
Shifted right by 1100000000000001000101010111010011
Rotated left by 2111011110110000000000000000000000
Rotated right by 1111011110110000000000000000000000

Note that for a 32-bit primitive data type, a left-rotation of 5 is the same as a left-rotation of 37 and a right rotation of 27.

Implement these functions.

unsigned int  left_rotate( unsigned int value, std::size_t n );
unsigned int right_rotate( unsigned int value, std::size_t n );

Templated

For a templated data type, you will have to recall that the size of the type can be found using the sizeof operator.

template <typename T>
T  left_rotate( T value, std::size_t n );

template <typename T>
T right_rotate( T value, std::size_t n );