First discuss about what is bits clearing?
- Number 12 is represented as 1100 in binary format. Mathematical representation like (12)10 = (1100)2. So Number (1100)2 then complete bits clearing result is (0000)2, means set all bit to 0, this is called complete/all bits clearing.
- But in some cases we need to clear particular bit of Number. For example (1100)2 clear 2st bit only, then result become (1000)2, (bit counted from right to left, counting started with number 0), this is single bit clearing.
- Now we can start with clear bits of number with given range. For example (1101)2 clear bits from 1st to 3rd bit, then result become (0001)2. This is given rang bits clearing.
All bits clearing:
Suppose N is unsigned integer value.
Then we can code in C like this:
Then we can code in C like this:
Then we can code in C like this:
unsigned int all_bits_clearing(unsigned int N) { return N & 0 }
Single bit clearing:
Single bit clearing is possible with following method:
Input is (1100)2 and 2nd bit need to clear, then first create binary number which contain 1 as a bit value at 2nd bit. Suppose number is X, that we can create X like this 1 << 2 = (0100)2, Now do bitwise complement of (0100)2, so binary after bitwise complement is (1011)2, do AND operation of both numbers (1100)2 & (1011)2 = (1000)2
Then we can code in C like this:
unsigned int single_bit_clearing(unsigned int N, unsigned int k) { return (N & (~(1 << k))); }
Clear a given range of bits:
Input is (1101)2 and range is from 1st bit to 3rd bit. Then first create binary number which contain 0 as bit value from 1st bit to 3rd bit and other bits values are 1. So required value is (0001)2. But how to created (0001)2 using given rang ? So first find range difference i.e. 3 -1 = 2, then (1 << (2+1)) -1 = (7)10 = (0111)2 , Now shift this value with lowest rang value (0111)2 << 1 = (1110)2, Now do bitwise complement of (1110)2, so binary value after bitwise complement is (0001)2 , Now do AND operation of Input value (1101)2 and (0001)2 ,
(1100)2 & (0001)2 = (0001)2
Then we can code in C like this:
unsigned int rang_toggling(unsigned int N, unsigned int k , unsigned int l) { //Here l > k return N & ~((1<<(l-k)+1)-1)<<k; }
No comments:
Post a Comment