Say, I have a integer like 10101
, I would like to unset the third bit to get 10001
; if I have 10001
, I will still get 10001
; how can I achieve it?
unset(int i, int j) int i= 10101 or 10000 int j = 00100
Say, I have a integer like 10101
, I would like to unset the third bit to get 10001
; if I have 10001
, I will still get 10001
; how can I achieve it?
unset(int i, int j) int i= 10101 or 10000 int j = 00100
Assuming that you are indexing bits from the right, this should work to unset a particular bit in value
:
int mask = 1
You can set the bit using similar code:
value |= mask;
where mask
is as before. (This assumes that bit indexing starts at 0.)
To clear or unset a bit
Use the bitwise AND operator (&) to clear a bit.
number &= ~(1
That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.
NOTE : here x is the position of bit starting from 0 to LSB.
If you are dealing with litterals, then you can just work with the hex numbers. Converting your bit patterns to hex numbers:
10101 => 0x15 00100 => 0x04
So the following C code would set b
to the result you want.
int a = 0x15; int b = a & ~( 0x04 );
If you wanted something generic you could have a C function (with all range checking removed) like
int clearBit( int value, int bit ) { // Assume we count bits starting at 1 return value & ~( 1
In C and C++ use bit wise AND operator to form an AND mask:
10101 & 10001
You can toggle the nth bit
result = number ^ (1