The C language even allows us to use struct
and union
to be able to directly determine the value of one or more bits with the =
operator.
This functionality is little used - and anyway, it requires you to define a Union by naming bits (or fields with different sizes of bits).
To change a "generic" bit by one byte, the most common is:
- create a number with the bit in the right position
- Use the "|" operation ("or" binary) to set the bit
This is if you want to pass the bit always from 0 to 1. The use of "xor" will always reverse the bit. And if you want to delete a bit, then the process involves creating a mask where the desired bit has the value "0", and apply the "&" operation.
We can do a function to set or reset a bit that does this: receive a pointer for the byte to be changed, the bit position, and the desired value. We create the byte with the bit in "1" in the correct position - (using the <<
operator), from it we create a mask with that bit at zero, and apply the bit with the value sent. In C:
void altera_bit(char *alvo, char posicao, char valor) {
char mascara = ~(1 << posicao);
*alvo = (*alvo & mascara) | (valor << posicao);
}