0

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

  • Use masking techniques as in [Link][1] [1]: http://stackoverflow.com/questions/28231740/rational-comparison-of-bits/28233250#28233250 – Waqas Shabbir Feb 13 '15 at 04:33

4 Answers4

2

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.

Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55
1

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)

Spencer D
  • 3,376
  • 2
  • 27
  • 43
0

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".

Gort the Robot
  • 2,329
  • 16
  • 21
0

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);
Valeri Atamaniouk
  • 5,125
  • 2
  • 16
  • 18