Friday, April 8, 2011

#C_CODE: Extract bits

#include <stdio.h>
 
int main()
{
 int num,bits,pos,res;

 printf("Enter the num: ");
 scanf("%d",&num);
 printf("\nEnter the no. of bits to be extracted: ");
 scanf("%d",&bits);
 printf("\nEnter the pos(0 onwards): ");
 scanf("%d",&pos);
    
 res = (num >> (pos + 1 - bits)) & (~(~0 << bits));
 printf("\nThe extracted bits are: %d",res  );
 fflush(stdin);
 getchar();
}


EXAMPLE: num = 233(0b11101001), pos = 5, bits = 3, Result = 5(0b101)


Ref: C Programming Language - K&R

No comments: