How to connect a bit to a number?

Asked

Viewed 855 times

9

There are situations that we use numbers to load flags, That is, every bit, or set of bits, means something. Or we need to manipulate some data according to its bits, maybe it has to do with colors or something that bits individually end up having a special meaning. In cases like this what is the simplest way to turn on a specific bit knowing what position it should be in. And how to turn it off or reverse its value?

1 answer

6


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.