Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to circular shift an array of 4 chars?

Tags:

c

I have an array of four unsigned chars. I want to treat it like a 32-bit number (assume the upper bits of the char are don't care. I only care about the lower 8-bits). Then, I want to circularly shift it by an arbitrary number of places. I've got a few different shift sizes, all determined at compile-time.

E.g.

unsigned char a[4] = {0x81, 0x1, 0x1, 0x2};
circular_left_shift(a, 1);
/* a is now { 0x2, 0x2, 0x2, 0x5 } */

Edit: To everyone wondering why I didn't mention CHAR_BIT != 8, because this is standard C. I didn't specify a platform, so why are you assuming one?

like image 292
matt_h Avatar asked Oct 12 '10 19:10

matt_h


1 Answers

static void rotate_left(uint8_t *d, uint8_t *s, uint8_t bits)
{
   const uint8_t octetshifts = bits / 8;
   const uint8_t bitshift = bits % 8;
   const uint8_t bitsleft = (8 - bitshift);
   const uint8_t lm = (1 << bitshift) - 1;
   const uint8_t um = ~lm;
   int i;

   for (i = 0; i < 4; i++)
   {
       d[(i + 4 - octetshifts) % 4] =
           ((s[i] << bitshift) & um) | 
           ((s[(i + 1) % 4] >> bitsleft) & lm);
   }
}   

Obviously

like image 136
Kevin Zhou Avatar answered Oct 04 '22 08:10

Kevin Zhou