Circular left shift and circular right shift on integer

© Parineeth M R

Question 36. Implement circular shift left and circular shift right on an unsigned integer


Let n be the number of bits to shift. Let m be the total number of bits present in the integer. If we circular shift an integer m times then we get back the original integer. So the actual number of shifts we need to perform is n % m.

The functions for circular shift left (also called left shift rotate) and circular shift right (right shift rotate) are given below

C/C++


/*
input: input value which has to be circularly shifted left
n: number of positions to shift
Return value: result after circularly left shifting input
*/
unsigned int circular_left_shift(unsigned int input, int n)
{
	unsigned int size = sizeof(unsigned int) * 8;
	unsigned int result;
	
	n = n % size;
	result = input << n | input >> (size - n);
	return result;
}


/*
input: input value which has to be circularly shifted right
n: number of positions to shift
Return value: result after circularly right shifting input
*/
unsigned int circular_right_shift(unsigned int input, int n)
{
	unsigned int size = sizeof(int) * 8;
	unsigned int result;

	n = n % size;
	result = input >> n | input << (size - n);
	return result;
}



Java


/*
input: input value which has to be circularly shifted left
n: number of positions to shift
Return value: result after circularly left shifting input
*/
public static int circularLeftShift(int input, int n) {
	int numBitsInInt = 32;
	n = n % numBitsInInt;
	int result = input << n | input >>> (numBitsInInt - n);
	return result;
}


/*
input: input value which has to be circularly shifted right
n: number of positions to shift
Return value: result after circularly right shifting input
*/
public static int circularRightShift(int input, int n) {
	int numBitsInInt = 32;
	n = n % numBitsInInt;
	int result = input >>> n | input << (numBitsInInt - n);
	return result;
}




Python


#value: input value which has to be circularly shifted left
#n: number of positions to shift
#Return value: result after circularly left shifting input value
def circular_left_shift(value, n) :
	num_bits_in_int = 32
	n = n % num_bits_in_int
	mask = (1 << num_bits_in_int) - 1
	result = (value << n) | (value >> (num_bits_in_int - n))
	result = result & mask
	return result


#value: input value which has to be circularly shifted right
#n: number of positions to shift
#Return value: result after circularly right shifting input
def circular_right_shift(value, n) :
	num_bits_in_int = 32
	n = n % num_bits_in_int
	mask = (1 << num_bits_in_int) - 1
	result = (value >> n) | (value << (num_bits_in_int - n))
	result = result & mask
	return result