# Writing binary data to a file (bits).

• 04-05-2004
OOPboredom
Writing binary data to a file (bits).
I'm under the assumption that the smallest amount of data you can write to a file is a byte - 4 bits. I have a problem, working with a compressed file, that I need to solve.

I have the algorithm and everything, but I'm stuck on two parts, which I could not find supporting information for. I need to be able to read 3 bits from a file and then from that number, determine how many bits to write out - from 1-6.

How can I possibly write out a variable amount of bits? I figure that if I need to read 3 bits from a file, I can just read in a char (4 bits), take those 4 bits, and do bit operations on them to single what it would be if it were just a 3 bit object.

Does anybody have any ideas/suggestions? Thanks.

p.s. I'm not writing any code at the moment, I'm just trying to get the design details down.
• 04-05-2004
ggs
you use bitwise operators, like &, |, <<, >> and the like.

you'll still have to deal with your file access operations in bytes, but you can pack these bytes with variable-sized bitfields.

it's barrels of fun! :(
• 04-05-2004
SMurf
Erm, a byte is actually 8 bits, on the Intel x86 platform and many others, at least.

It's a common problem that can be overcome by the use of bit masking and shifting. Let's suppose you wanted the first 3 bits from a char/unsigned char (8 bits):-
Code:

```0 1 0 1 0 1 0 1 \___/```
In order to get those bits in C, you'd read the byte in, mask it so only the top 3 bits are relevant and shift it 5 bits to the right so the bits are at the bottom and will be arithmatically correct:-
Code:

```unsigned char byte, bits; byte = getc(fp); bits = (byte & 0xE0) >> 5;```
That'll give you a value of 0 to 7 for your three bits.

You can ignore the mask and just shift if you don't need anything else from those 8 bits. :)