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
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)