Set all the bits in given range of unsigned int

First discuss about what is bits setting? 
  1. Number 12 is represented as 1100 in binary format. Mathematical representation like (12)10 = (1100)2So Number (1100)2 then complete bits setting result is (1111)2, means set all bit to 1, this is called complete/all bits setting.
  2. But in some cases we need to set particular bit of Number. For example (1100)2 set 1st bit only, then result become (1110)2, (bit counted from right to left, counting started with number 0), this is single bit setting.
  3. Now we can start with set bits of number with given range. For example (1100)2 set bits from 1st to 3rd bit, then result become (1110)2. This is given rang bits setting.
Now we can start with how to code this in C.

All bits setting:

Suppose N is unsigned integer value.
 Then we can code in C like this:
unsigned int all_bits_setting(unsigned int N)
{
  return N | ~0
}


Single bit setting:

Single bit setting is possible with following method: 
Input is (1100)2  and 2nd bit need to set, then first create binary number which contain 1 as a bit value at 1nd bit. Suppose number is X, that we can create X like this 1 << 2 = (0010)2, do OR operation of both numbers (1100)2  | (0010)2 = (1110)2

Then we can code in C like this:

unsigned int single_bit_setting(unsigned int N, unsigned int k)
{
  return (N | (1 << k)); 
}

Set given range of bits:

Input is (1100)2  and range is from 1st bit to 3rd bit. Then first create binary number which contain 1 as bit value from 1st bit to 3rd bit and other bits values are 0. So required value is (1110)2. But how to created (1110)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 OR operation of Input value  (1101)2 and (1110)2 ,
(1100)2 | (1110)=  (1110)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