The C language even allows us to use struct
and union
to be able to direct the value of one or more bits with the operator =
.
This functionality is rarely used - and anyway, requires you to define a Union by naming bits (or fields with different bit sizes).
To change a "generic" bit into a byte, the most common is:
- create a number with the bit at the right position
- Use operation "|" ("or" binary) to set the bit
This is if you want to always pass the bit from 0 to 1. Using the "xor" will always invert the bit. And if you want to delete a bit, then the process involves creating a mask in which the desired bit has the value "0", and applying the operation "&".
We can do a function to set or reset a bit that does this: get a pointer to the byte to change, the bit position, and the desired value. We create the byte with the bit in "1" at the correct position - (using the operator <<
), from it we create a mask with this 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);
}
Thank you all!
– LUIZ