12
I want to change a bit
an integer variable in C
/CSS
for pic
.
Ex: change some bit to turn another number.
15 = 0b00001111 -> 0b00001101 = 13.
12
I want to change a bit
an integer variable in C
/CSS
for pic
.
Ex: change some bit to turn another number.
15 = 0b00001111 -> 0b00001101 = 13.
11
As a general rule, to "delete" a bit, that’s it:
valor &= ~( 1 << bitPos);
and to "light up," that’s it:
valor |= 1 << bitPos;
whereas bitPos
is the bit position, zero being the rightmost.
See working on IDEONE.
If you want to manipulate more than one bit at a time, 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 on 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 Mr Bruno, there are bit_set(número, bit)
and bit_clear(número, bit)
, see corresponding answer.
Just to complement, if someone is interested in Arduino equivalent, we have similar functions to those of CCS:
https://www.arduino.cc/en/Reference/HomePage
We have these two functions:
Whereas x
is the value to be changed, and n
the bit to be changed, being 0
the right most bit.
4
The CCS has the functions bit_set(número, bit)
, which arrow the bit as 1
and bit_clear(número, bit)
that resets the bit as 0
!
Browser other questions tagged c pic
You are not signed in. Login or sign up in order to post.
The prefix 0b for binary numbers is not standard for C, it is an extension of gcc (and probably other compilers, but as far as I know the Microsoft C compiler, for example, does not have this extension).
– zentrunix
@Josex I could have mentioned that it is C++14 (by the way, I think it was ridiculous that it took so long), although in the context of the question I put it for visualization (and the author used it in the original code, which was the target of the answer). Anyway, I passed for comments not to confuse, in case someone decides to copy and compile as it is in some context different from the author.
– Bacco
C++14...there is no C14...
– zentrunix
My experience is that hexadecimals are usually used to work with bits, both in C and C++. I think it’s even more practical than using the 0b prefix.
– zentrunix
@Joséx. Or more practical, or perhaps consequence of the habit of using without for lack of option at first. For things like enums, it’s really easy to see 1,2,4,8,10,20,40,80 but for a character map or bit masks, for example, base 2 gives instant visualization. Now, of course each should wear whatever is most comfortable, provided that in the team pattern.
– Bacco