c – 如何将一个字节数组移位12位

前端之家收集整理的这篇文章主要介绍了c – 如何将一个字节数组移位12位前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将字节数组的内容向左移位12位.

例如,从这个uint8_t类型的数组开始[10]:

{0x00,0x00,0x0A,0xBC}

我想把它向左移位12位,结果是:

{0x00,0xAB,0xC0,0x00}

解决方法

Hurray为指针!

代码通过向前查看每个字节12位并将正确的位向前复制. 12位是下一个字节的下半部分(nybble)和2个字节的上半部分.

unsigned char length = 10;
unsigned char data[10] = {0x0,0x0,0xBC};
unsigned char *shift = data;
while (shift < data+(length-2)) {
    *shift = (*(shift+1)&0x0F)<<4 | (*(shift+2)&0xF0)>>4;
    shift++;
}
*(data+length-2) = (*(data+length-1)&0x0F)<<4;
*(data+length-1) = 0x00;

Justin wrote:
@Mike,your solution works,but does not carry.

那么我会说一个正常的移位操作就是这样(称为溢出),只是让额外的位从右边或左边掉下来.如果您想要 – 只需保存12位,然后再开始移动即可轻松携带.也许你想要一个循环移位,把溢出的位回到底部?也许你想重新配置数组并使其更大?将溢出返回给调用者?如果非零数据溢出,返回一个布尔值?你必须为你定义什么携带手段.

unsigned char overflow[2];
*overflow = (*data&0xF0)>>4;
*(overflow+1) = (*data&0x0F)<<4 | (*(data+1)&0xF0)>>4;
while (shift < data+(length-2)) {
    /* normal shifting */
}  
/* now would be the time to copy it back if you want to carry it somewhere */
*(data+length-2) = (*(data+length-1)&0x0F)<<4 | (*(overflow)&0x0F);
*(data+length-1) = *(overflow+1);  

/* You could return a 16-bit carry int,* but endian-ness makes that look weird 
 * if you care about the physical layout */
unsigned short carry = *(overflow+1)<<8 | *overflow;

猜你在找的C&C++相关文章