0

I'm working on rotating the bytes of integer numbers.
The first thing I'm attempting to do is grabbing the lower N amount of bits and higher n amount of bits. Because after I call my shift(n) it will cut those bits off either at the higher and or lower end depending if it's rotating left or right.
So far I have my low working and it's grabbing the correct bits. My high is not grabbing the correct bits I'm trying to use k and m to grab my high bits.
After I call my shift I need to add the bits that were cut off back onto the opposite side of where I grabbed it from.
I'm struggling with getting the logic of how I would add back those cut of bits and how to grab the high n amount of bits. And tips and suggestions would be greatly appreciated.

NBITS -> the amount of bits in the byte
Shift(n) -> shifts n amount of bits to either left or right depending if n is positive or negative

void shift(int n)         // If n > 0, shifts bits right n places; if n < 0,left
{   
    if (n > 0)
        bits = bits >> n;
    else if (n < 0)
        bits = bits << -n;
}

void rotate(int n)
{   
    int k = NBITS - 1; // last position
    int m = (NBITS - 1) - n + 1; // to desired position
    int low = bits & ((1 << n) - 1);
    int high = (bits & (((1 << (m - k + 1)) - 1) << k)) >> k;
   
    assert(abs(n) <= NBITS);
    if (n > 0) { // rotate right n places 
        shift(n);
        //put back cut off bits
    }
    else if (n < 0) { // rotates left
        shift(n);
        //put back cut off bits
    }
}
Jack Lilhammers
  • 1,207
  • 7
  • 19
Derek
  • 1
  • 1

0 Answers0