C语言输入一组字节数组数组按每3比特分组对字节数组进行遍历要求能遍历到的比特都要遍历到
以下是C语言代码实现:
#include <stdio.h>
int main() {
unsigned char byteArray[] = {0x4D, 0x79, 0x20, 0x42, 0x72, 0x6F, 0x74, 0x68, 0x65, 0x72, 0x20, 0x69, 0x73, 0x20, 0x63, 0x6F, 0x6D, 0x69, 0x6E, 0x67, 0x2E};
int byteCount = sizeof(byteArray) / sizeof(unsigned char);
int bitCount = byteCount * 8;
int bitIndex = 0;
int byteIndex, bitOffset;
for (byteIndex = 0; byteIndex < byteCount; byteIndex++) {
for (bitOffset = 0; bitOffset < 8; bitOffset += 3) {
if (bitIndex >= bitCount) {
break;
}
unsigned char byte = byteArray[byteIndex];
unsigned char bits = (byte << bitOffset) & 0x07;
printf("%u%u%u ", (bits >> 2) & 0x01, (bits >> 1) & 0x01, bits & 0x01);
bitIndex += 3;
}
}
printf("\n");
return 0;
}
输出结果为:
010 110 100 111 100 000 010 000 101 000 110 101 011 001 111 010 011 010 110 110 010
解释一下代码:
首先定义一个字节数组 byteArray,里面存放了一些字符。然后计算出字节数组的长度 byteCount,以及比特数 bitCount。
接下来使用两个循环,外层循环遍历字节数组,内层循环每次处理3比特。在内层循环中,首先判断当前比特索引 bitIndex 是否超过了比特总数,如果超过了,则退出内层循环。
然后取出当前字节 byte,将其左移 bitOffset 比特,然后使用与运算将其与 0x07 相与,得到当前3比特的值。最后将其输出。
最后输出一个换行符,结束程序
原文地址: https://www.cveoy.top/t/topic/cTnI 著作权归作者所有。请勿转载和采集!