c++ - How do you set, clear, and toggle a single bit? -
how set, clear, , toggle bit in c/c++?
setting bit
use bitwise or operator (|
) set bit.
number |= 1 << x;
that set bit x
.
clearing bit
use bitwise , operator (&
) clear bit.
number &= ~(1 << x);
that clear bit x
. must invert bit string bitwise not operator (~
), , it.
toggling bit
the xor operator (^
) can used toggle bit.
number ^= 1 << x;
that toggle bit x
.
checking bit
you didn't ask might add it.
to check bit, shift number x right, bitwise , it:
bit = (number >> x) & 1;
that put value of bit x
variable bit
.
changing nth bit x
setting n
th bit either 1
or 0
can achieved following:
number ^= (-x ^ number) & (1 << n);
bit n
set if x
1
, , cleared if x
0
.
Comments
Post a Comment