Puppy
Puppy

Reputation: 146968

Expressing rotation where bits are represented in array

I've got a series of bits, represented by pointers.

Bit* bits[32];

Now I need to implement the binary right rotate operator. I've got that the first part is a right shift of the same amount, which deals with all the bits which did not wrap around, but I'm not sure what to do about the ones which do wrap around.

How can I determine which bits end up in which positions in the end results?

So far, I've got

ExpressionHolder rotate(unsigned int other) const {
    ExpressionHolder out;
    out.e = new Expression;
    for(int i = 0; i < (32 - other); i++) {
        out.e->bits[i] = e->bits[i + other];
    }  
    for(int i = (32 - other); i < 32; i++) {
        out.e->bits[i] = e->bits[31 - i];
    }
    return out;
}

Is this correct?

Upvotes: 3

Views: 107

Answers (2)

Praetorian
Praetorian

Reputation: 109189

std::rotate_copy should do the trick

ExpressionHolder rotate( ExpressionHolder const& in, std::size_t count )
{
  ExpressionHolder out;
  out.e = new Expression();

  std::rotate_copy( in.e->bit, in.e->bit + 32 - count, in.e->bit + 32, out.e->bit );
  return out;
}

Upvotes: 4

Captain Giraffe
Captain Giraffe

Reputation: 14705

Quantum mechanics dictates that bits are always in a superposition of one and zero. So we can never be sure of the actual bit value of your pointer until we look at *e.bits[i].

But then after we look a straightforward

for(int i = 0; i < 32; i++)
     out.e->bits[i] = e->bits[(i + other) %32];

should do the trick.

Upvotes: 3

Related Questions