I want to change an integer variable to bit
in C
/ CSS
to pic
.
Ex: change some bit to turn another number.
15 = 0b00001111 - > 0b00001101 = 13.
I want to change an integer variable to bit
in C
/ CSS
to pic
.
Ex: change some bit to turn another number.
15 = 0b00001111 - > 0b00001101 = 13.
In general, to "erase" a bit, this is:
valor &= ~( 1 << bitPos);
and to "light up", that's it:
valor |= 1 << bitPos;
where bitPos
is the position of the bit, zero being the rightmost one.
See working at IDEONE .
If you want to handle more than one bit at a time, you can do so too:
int valor = 15 // 0b00001111;
int mascara = 70 // 0b01000101;
//BIT: 76543210
resultado1 = valor | mascara; // 0b01001111 ("acendi" os bits 0,2 e 6)
resultado2 = valor & ~mascara; // 0b00001010 ("apaguei" os bits 0,2 e 6)
See working at IDEONE
int valor = 15 // 0b00001111;
valor &= ~( 1 << 0 ); // valor = 14 ( 0b00001110 ) - "apagamos" o bit 0
valor |= 1 << 5; // valor = 46 ( 0b00101110 ) - "acendemos" o bit 5
valor &= ~( 1 << 1 ); // valor = 44 ( 0b00101100 ) - "apagamos" o bit 1
valor |= 1 << 0; // valor = 45 ( 0b00101101 ) - "acendemos" o bit 0
According to colleague Bruno, there are the functions bit_set(número, bit)
and bit_clear(número, bit)
, see corresponding answer.
Just to complement, if anyone is interested in Arduino equivalent, we have functions similar to those of CCS:
We have these two functions:
Since x
is the value to be changed, and n
is the bit to be changed, 0
is the rightmost bit.
CCS has the functions bit_set(número, bit)
, which sets the bit to 1
and bit_clear(número, bit)
, which sets the bit to 0
!