# reading and writing a single bit to a file

This is a discussion on reading and writing a single bit to a file within the C Programming forums, part of the General Programming Boards category; is there any way to read/write a single bit from/to a file in c ? I'm trying to creat a ...

1. ## is reading and writing a single bit to a file possible?

is there any way to read/write a single bit from/to a file in c ?

I'm trying to creat a simulation (i'm a physicist not a programmer...) and the data is boolean (meaning yes or no) and the natural way to store it is in bits (dah..).
since there's TONS of data the files will be HUGE if i'd use integers. so i need to know how to handle single bits.

2. Read a char and then use bit masking to get at a single bit.

3. pardon me , but I have no idea what "bit masking means". . .
p.s - do you mean reading a single character using fread or getc?

4. You can only read a character at a time, not a bit at a time. So you need to read a character, and then look at its particular bits, and modify one of them, and then write out the character.

Suppose your piece of data is in the fourth-lowest bit in the character. Your character might be filled with some data. Suppose its eight bits happen to represent the number 98:

Code:
```01100010
^   \$```
I put the arrow to point at the fourth-lowest bit in the character. (Realize that I like to start at zero. The dollar sign is beneath the zero-lowest bit in the character.)

Now let's look at the number 16:
Code:
```00010000
^```
If we bitwise-or those numbers together, we get:
Code:
```01100010 <- operand
00010000 <- operand
01110010 <- result```
We've changed the fourth bit of the number!

In general, following the spirit of the above example, you can use the bitwise operations &, |, ^, and ~ to change the bits of a number. Here are some sample functions.

Code:
```unsigned int turn_on_but(unsigned int n, int bitnum) {
return n | (1 << bitnum);
}

unsigned int turn_off_bit(unsigned int n, int bitnum) {
return n & (~ (1 << bitnum));
}

unsigned int flip_bit(unsigned int n, int bitnum) {
return n ^ (1 << bitnum);
}

/* Returns 1 or 0 */
unsigned int get_bit(unsigned int n, int bitnum) {
return (n & (1 << bitnum)) >> bitnum;
}

/* Expects 1 or 0 */
unsigned int put_bit(unsigned int n, int bitnum, int bit) {
return n | (bit << bitnum);
}```
So you could read a character, call one of these functions (getting a specific bit from the character), use these functions to write a bit to the right place in the character, and write the new character, if you wanted. You can only read or write a character at a time, though.

This is (not exclusively) what bit masking is. For example, the number 16 (00010000 in binary) is a 'mask' that only lets the fourth bit shine through when 'bitwise anded' with a number.

5. Bit Manipulation

You could also use 'Bit Fields', do a search.