Friday, April 8, 2011

#C_CODE: Clear 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 cleared: ");
 scanf("%d",&bits);
 printf("\nEnter the pos(0 onwards): ");
 scanf("%d",&pos);
    
 printf("The result: %d\n", 
( num & (~((~(~0 << bits)) << pos + 1 - bits)) ) );
 fflush(stdin);
 getchar(); 
}

Example: num = 255(0b1111,1111), bits = 3, pos = 5, Result = 199(0b11000111)


Ref: C Programming Language - K&R

No comments: