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:

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:

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.