To manipulate bits the most common is to use the operators of |
(or
), &
(and
) And ^
(xor
), with support from ~
(complement). The operator of shift or bit shifting is usually important to get to the desired bit if what you know is its position. These operators are usually present in most languages with the same semantics, so everything that works here should work for other languages. Several questions talk about it:
Examples of set, reset, toggle and test:
#include <stdio.h>
int main(void) {
int posicao = 6; //posicao do bit (equivale ao 64)
int valor = 0;
valor |= 1 << posicao; //ligando o bit
printf("Ligou o bit: %d\n", valor);
int resultado = (valor >> posicao) & 1; //verificando valor do bit
printf("O bit está: %d\n", resultado);
valor &= ~(1 << posicao); //limpando o bit
printf("Desligou o bit: %d\n", valor);
resultado = (valor >> posicao) & 1; //verificando valor do bit
printf("O bit está: %d\n", resultado);
valor ^= 1 << posicao; //invertendo um bit
printf("Inverteu o bit: %d\n", valor);
valor |= 16; //ligando o bit pelo seu valor
printf("Ligou o 4. bit: %d\n", valor);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
It is common for some people to create functions that do just that to be easier to use and remember.