How could I write "1" bit to the binary file?

I need to compress an image(by block truncation),but I don't know
how to "write one bit" into the binary file, I have checked the function of C, the smallest unit are "byte" but not bit, if there are no way to "write one bit" into the binary file directly, then I would have to do some management before I write data into the file.

Thanks a lot
You can't write a bit to a file directly. You have to "collect" bits until you have at least one byte.
It's recommended to create a stream class that handles the bit shifting and packing.
here ya go:
1
2
3
4
5
6
7
8
int putbit(FILE *f,char buf[2],bool bit){//writes the bit to the file, when the buffer is full.
	if(buf[0]==0){
		fputc(buf[1],f);
		buf[0]=7;
		buf[1]=0;
	}
	buf[1]+=(int)bit<<buf[0]--;
}

use like this:
1
2
3
4
5
6
7
8
9
char buf[2]={7,0};
putbit(stdout,buf,0);
putbit(stdout,buf,0);
putbit(stdout,buf,1);
putbit(stdout,buf,1);
putbit(stdout,buf,0);
putbit(stdout,buf,0);
putbit(stdout,buf,0);
putbit(stdout,buf,0);

Allocate a separate 2-character buffer for each file you output to.
Thank you very much

ps: rocketboy9000 (135), I haven't tryed your code yet.
You give me a concept and I could
alter it to fit my request, thank you
Last edited on
Topic archived. No new replies allowed.