Rotate Right

How would you create a rotate right function with >> or << ?
Ex: 0111 = 7
1011 = 11
1101 = 13
1110 = 14
closed account (zb0S216C)
Well, << & >> shift all the bits of their operands left and right, respectively. However, for their behaviour to change with specific types, you'll have to overload them. For instance:

1
2
3
4
5
6
7
8
9
10
// Overload:
Some_Type operator >> (const Some_Type &pObject)
{
    // ...
}

Some_Type &operator << (const Some_Type &pObject)
{
    // ...
}

Wazzak
Last edited on
int R_rotate(char Op1)
{
cout << "im r rotate ";
int i = (int)Op1;
int num;
if(i >= '0' && i <= '9')
{
i = i-48;
}
if (i >= 'A' && i <= 'F')
{
i = i-55;
}

i = i << 4;
for (int s = 0; s < 3; s++)
{
i = i >> 1;
if ( i & 8)
{
i = i | 128;
}
}
i = i >> 4;
cout << i << endl;

}

this works pretty well
Consider rotate right by one:

given: 1010
LSB is 0: 1010
shift right 1: x101
clear MSB: 0101

again: 0101
LSB is 1
shift right 1: x010
set MSB: 1010

The toughest part is figuring out how to handle the MSB. There are a variety of ways, but the simplest is to just clear or set as appropriate. You have to know how big your integer object is, also.

It makes a difference whether or not your integers are signed. Technically, in C (and C++), shift right is not defined for signed objects. (IIRC.) Many compilers will use a sign-extend shift for signed integers, though. (You might just want to stick to unsigned integers.)

Hope this helps.
Topic archived. No new replies allowed.