简体   繁体   中英

How to write individual bytes to filein C++

GIven the fact that I generate a string containing "0" and "1" of a random length, how can I write the data to a file as bits instead of ascii text ?

Given my random string has 12 bits, I know that I should write 2 bytes (or add 4 more 0 bits to make 16 bits) in order to write the 1st byte and the 2nd byte.

Regardless of the size, given I have an array of char[8] or int[8] or a string, how can I write each individual group of bits as one byte in the output file?

I've googled a lot everywhere (it's my 3rd day looking for an answer) and didn't understand how to do it.

Thank you.

You don't do I/O with an array of bits.

Instead, you do two separate steps. First, convert your array of bits to a number. Then, do binary file I/O using that number.

For the first step, the types uint8_t and uint16_t found in <stdint.h> and the bit manipulation operators << (shift left) and | (or) will be useful.

You haven't said what API you're using, so I'm going to assume you're using I/O streams. To write data to the stream just do this:

f.write(buf, len);

You can't write single bits, the best granularity you are going to get is bytes. If you want bits you will have to do some bitwise work to your byte buffer before you write it.

If you want to pack your 8 element array of chars into one byte you can do something like this:

char data[8] = ...;
char byte = 0;
for (unsigned i = 0; i != 8; ++i)
{
    byte |= (data[i] & 1) << i;
}
f.put(byte);

If data contains ASCII '0' or '1' characters rather than actual 0 or 1 bits replace the |= line with this:

byte |= (data[i] == '1') << i;

Make an unsigned char out of the bits in an array:

unsigned char make_byte(char input[8]) { 
    unsigned char result = 0;
    for (int i=0; i<8; i++)         
        if (input[i] != '0')
           result |= (1 << i);       
    return result;
}

This assumes input[0] should become the least significant bit in the byte, and input[7] the most significant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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