如何循环移位的4字符数组? [英] How to circular shift an array of 4 chars?

查看:129
本文介绍了如何循环移位的4字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四个无符号的字符数组。我要像对待一个32位数字(假设焦炭的高位不在乎。我只在乎低8位)。然后,我想通过循环地方任意数量转向它。我有几个不同尺寸的转变,都在编译时确定的。

例如

  unsigned char型A [4] = {0×81,为0x1,为0x1,0X2};
circular_left_shift(一,1);
/ *一个是现在{0X2,0X2,0X2,0x5的} * /

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


解决方案

 静态无效rotate_left(uint8_t有* D,uint8_t有* S,uint8_t有位)
{
   常量uint8_t有octetshifts =比特/ 8;
   常量uint8_t有bitshift位= 8%;
   常量uint8_t有bitsleft =(8 - bitshift);
   常量uint8_t有流明=(1 <<;&下; bitshift) - 1;
   常量uint8_t有UM =〜流明;
   INT I;   对于(I = 0; I&下; 4;我+ +)
   {
       D [第(i + 4 - octetshifts)%4] =
           ((S [1] - ;&下; bitshift)及微米)|
           ((S [第(i + 1)%4]≥&GT; bitsleft)及流明);
   }
}

显然

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?

解决方案

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

这篇关于如何循环移位的4字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆