# Extract k bits from p position

This program extracts k bits from given position say p

Logic:
1) right shift the number by p-1
2)set k bits

Do and of 1 & 2

Same question can be asked to extract from say p to k
then p =p but k = k-p +1

Implementation:

``````#include <stdio.h>
#define MAX_BITS sizeof(int) * 8

void display_binary(int num)
{
int i =0;
for(i = MAX_BITS -1; i>=0;i--)
{
if( num & (1 <<i))
printf("1");
else
printf("0");
}
}

int extract_k_bits(int num, int k, int p)
{
return ( (num >> (p - 1)) & ( (1 << k) -1));
}

int main()
{
int num,k,p;

printf("\n Enter the number: ");
scanf("%d", &num);

printf("\n Enter the number of bit: ");
scanf("%d", &k);

printf("\n Enter the starting bit: ");
scanf("%d", &p);

printf("\n Original number is: %d  binary: ", num);
display_binary(num);

int res = extract_k_bits(num, k, p);
printf("\n The result is: %d binary: ", res);
display_binary(res);

return 0;
}``````

Output:

``````Enter the number: 171

Enter the number of bit: 5

Enter the starting bit: 2

Original number is: 171  binary: 00000000000000000000000010101011
The result is: 21 binary: 00000000000000000000000000010101``````

Categories: Data Structure and Algorithm