欢乐指点!
此代码通过向前看每个字节的12位并向前复制正确的位来工作.12位是下一个字节的下半部分(nybble)和2个字节的上半部分.
unsigned char length = 10; unsigned char data[10] = {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0A,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;
贾斯汀写道:
@Mike,你的解决方案有效,但不能随身携带.
好吧,我会说正常的移位操作就是这样(称为溢出),只是让额外的位从右边或左边掉下来.如果您愿意,它很容易携带 - 只需在开始移动之前保存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;