I know I can clear a single bit by using the bitwise operator &
number &= ~(1 << x);
But how would I be able to clear either the upper or lower half of a byte? For example, number = 99
99 = 0110 0011 and clearing the upper half we get 0000 0011
I know I can clear a single bit by using the bitwise operator &
number &= ~(1 << x);
But how would I be able to clear either the upper or lower half of a byte? For example, number = 99
99 = 0110 0011 and clearing the upper half we get 0000 0011
Just AND the byte with the mask you need: to clear the upper four bits, use n & 0x0F
, to clear the lower four bits, use n & 0xF0
.
You could say number &= 15;
. 15 is represented as 0000 1111
in binary which means the leading/upper 4 bits would be cleared away.
Likewise, to clear the trailing/lower 4 bits, you could then say number &= 240
because 240 is represented as 1111 0000
in binary.
For example, let's say number = 170
and we want to clear away the leading/upper four bits. 170
is represented as 1010 1010
in binary. So, if we do number &= 15
, we get:
1010 1010
& 0000 1111
-------------
0000 1010
(0000 1010
is 10
in binary)
Supposing, again, number = 170
and we want to clear the trailing/lower four bits, we can say: number &= 240
. When we do this, we get:
1010 1010
& 1111 0000
-------------
1010 0000
(1010 0000
is 160
in binary)
You want to do an and
with the bit-pattern showing what you want to keep.
So for your case:
number &= 0xf;
As 0xf
is 0000 1111
.
This is sometimes referred to as a "mask".
Clear lower half:
number &= ~0xF;
Higher half:
number &= ~0xF0;
The above works work int types. For larger types, you need to extend mask accordingly, for example:
number &= ~UINT64_C(0xF0);