Write a logic to extract P bits from Position N in an integer M.
#include<stdio.h> void Print_Num_inBinary(int); int main() { int num,pos,NoOfBits,i,val = 0,j=0; printf("Enter a Number = "); scanf("%d",&num); Print_Num_inBinary(num); printf("Enter a bit(Position) = "); scanf("%d",&pos); if(pos >=0 && pos <= (sizeof(int)*8-1)) { printf("How many bits you want to extract = "); scanf("%d",&NoOfBits); if((pos + NoOfBits) <= (sizeof(int)*8-1)) { for(i = pos;i < pos + NoOfBits;i++) { val = val | ((num >> i & 1) << j); j++; } Print_Num_inBinary(val); } else printf("Not Possible....\n"); } else { printf("\nInvalid Bit Positon\n"); } return 0; } void Print_Num_inBinary(int n) { int i; printf("\n%d Bit Binary Representation of a Number\n",sizeof(int)*8); for(i = ((sizeof(int)*8)-1);i >= 0;i--) { printf("%d",n >> i & 1); if(!(i%8)) printf(" "); } printf("\n\n"); }
Output
Enter a Number = 15 32 Bit Binary Representation of a Number 00000000 00000000 00000000 00001111 Enter a bit(Position) = 0 How many bits you want to extract = 3 32 Bit Binary Representation of a Number 00000000 00000000 00000000 00000111
Enter a Number = 255 32 Bit Binary Representation of a Number 00000000 00000000 00000000 11111111 Enter a bit(Position) = 5 How many bits you want to extract = 5 32 Bit Binary Representation of a Number 00000000 00000000 00000000 00000111