C语言输入一组字节数组数组按每3比特分组不足的情况下由下一字节补全按3比特遍历数组
以下是一个示例代码:
#include <stdio.h>
int main() {
unsigned char bytes[] = {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc};
int len = sizeof(bytes) / sizeof(unsigned char);
int i, j, bit;
unsigned char current = 0;
for (i = 0; i < len; i++) {
for (j = 0; j < 8; j++) {
bit = (bytes[i] >> (7 - j)) & 1;
current <<= 1;
current |= bit;
if ((i == len - 1) && (j == 7)) {
break;
}
if (j % 3 == 2) {
printf("%d ", current);
current = 0;
}
}
}
return 0;
}
该代码将输入的字节数组按位逐个遍历,每3比特组成一个新的3比特数字,并打印出来。如果字节数组不足3比特,会由下一字节补全并继续组成新数字
原文地址: https://www.cveoy.top/t/topic/cTtu 著作权归作者所有。请勿转载和采集!