如何循环移动4个字符的数组?

mat*_*t_h 10 c

我有一个由四个无符号字符组成的数组.我想把它当作一个32位数字(假设char的高位不关心.我只关心较低的8位).然后,我想循环移动任意数量的地方.我有一些不同的移位大小,都是在编译时确定的.

例如

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

编辑:大家都在想我为什么没有提到CHAR_BIT!= 8,因为这是标准C.我没有指定一个平台,那你为什么假设一个?

Kev*_*hou 5

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);
   }
}   
Run Code Online (Sandbox Code Playgroud)

明显

  • 我看到你已经假设了小端,但它可以很容易地修改成大端. (2认同)