简体   繁体   English

将字节转换为位数组? C

[英]Turn byte into array of bits? C

I want to read binary file byte at the time and then store bits of that byte into integer array.我想当时读取二进制文件字节,然后将该字节的位存储到整数数组中。 And similarly I want to write integer array of 1s and 0s (8 of them ) into binary file as bytes?同样,我想将 1 和 0(其中 8 个)的整数数组作为字节写入二进制文件?

If you have an array of bytes: 如果您有字节数组:

unsigned char bytes[10];

And want to change it into an array of bits: 并希望将其更改为一个位数组:

unsigned char bits[80];

And assuming you have 8 bits per byte, try this: 并假设每个字节有8位,请尝试以下操作:

int i;
for (i=0; i<sizeof(bytes)*8; i++) {
    bits[i] = ((1 << (i % 8)) & (bytes[i/8])) >> (i % 8);
}

In this loop, i loops through the total number of bits. 在此循环中, i循环浏览总位数。 The byte that a given bit lives at is i/8 , which as integer division rounds down. 给定位所驻留的字节为i/8 ,随着整数除法舍入。 The position of the bit within a byte is i%8 . 该字节在字节中的位置是i%8

First we create a mask for the desired bit: 首先,我们为所需的位创建一个掩码:

1 << (i % 8)

Then the desired byte: 然后是所需的字节:

bytes[i/8]

Then we perform a logical AND to clear all bits except the one we want. 然后,我们执行逻辑AND清除除所需位以外的所有位。

(1 << (i % 8)) & (bytes[i/8])

Then we shift the result right by the bit position to put the desired bit at the least significant bit. 然后,我们将结果右移一位位置,以将所需位放在最低有效位。 This gives us a value of 1 or 0. 这使我们的值为1或0。

Note also that the arrays in question are unsigned . 还要注意,所讨论的数组是unsigned That is required for the bit shifting to work properly. 这是位移位正常工作所必需的。

To switch back: 要切换回去:

int i;
memset(bytes, 0, sizeof(bytes));
for (i=0; i<sizeof(bytes)*8; i++) {
    bytes[i/8] |= bits[i] << (i % 8);
}

We start by clearing out the byte array, since we'll be setting each byte one bit at a time. 我们首先要清除字节数组,因为我们将一次将每个字节设置为一位。

Then we take the bit in question: 然后我们讨论一下:

bits[i]

Shift it into its position: 将其移至其位置:

bits[i] << (i % 8)

Then use a logical OR to set the appropriate byte; 然后使用逻辑或来设置适当的字节;

A simple C program to do the job on a byte array 'input' of size 'sz' would be:在大小为 'sz' 的字节数组 'input' 上完成这项工作的简单 C 程序是:

int i=0,j=0;
unsigned char mask = 0x01u;    

for (i=0;i<sz;i++)
        for (j=0;j<8;j++)
           output[8*i+j]=((unsigned char)input[i] >> j) & (unsigned char)(mask);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM