Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing bits to a file in C

Tags:

c

file

binary

I have this string: "101" I want to write it to a file, in C, not as text: "101" and so 8 bits x char. but directly use the string as bits: the bit "1", the bit "0" and the bit "1", so that the file will be of 3 bits.

Is it possibile? I searched on the web and I tried doing this:

char c[25] = "101"; FILE *binFile = fopen("binFile.bin", "wb"); int x = atoi(c); fwrite(&x, sizeof(x), 1, binFile); 

But at the end, when I verify files's bytes, Windows says me that it is 4bytes file! And not 3bits!

How can I do this, if it is possible? Thanks a lot.

like image 995
Francesco Bonizzi Avatar asked Nov 06 '12 14:11

Francesco Bonizzi


People also ask

How do you save a bit in a file?

You are going to need to have a one char buffer, and a count of the number of bits it holds. When that number reaches 8, you need to write it out, and reset the count to 0. You will also need a way to flush the buffer at the end. (Not that you cannot write 22 bits to a file - you can only write 16 or 24.

How do you write a bit?

To write you need to use bit-wise operators such as & ^ | & << >>. make sure to learn what they do. For example to have 00100100 you need to set the first bit to 1, and shift it with the << >> operators 5 times. if you want to continue writing you just continue to set the first bit and shift it.

How do you write bits to a file in C++?

To write a binary file in C++ use write method. It is used to write a given number of bytes on the given stream, starting at the position of the "put" pointer. The file is extended if the put pointer is currently at the end of the file.

How do you write a binary file?

To write to a binary fileUse the WriteAllBytes method, supplying the file path and name and the bytes to be written. This example appends the data array CustomerData to the file named CollectedData. dat .


1 Answers

All filesystems¹ deal with files in terms of bytes (and allocate storage space with a much larger granularity, 512 bytes at a time minimum). There's no way you are going to get a file that is 3 bits long.

The best you can do is use up one whole byte but ignore 5 of its bits. To do that (assuming that the number is always going to fit into a byte), convert the input string to an integral type:

long l = strtol(c, 0, 2); 

Then get its least significant byte:

unsigned char b = l & 0xffl; 

And write it to the file:

fwrite(&b, 1, 1, binFile); 

¹ Well, maybe not all. There might be some researchers somewhere that experiment with bit-sized filesystems. I wouldn't know.

like image 137
Jon Avatar answered Sep 21 '22 00:09

Jon