Thursday, January 6, 2011

Useful Bit-manipulation Functions


/* Function to print binary representation of a number */
void printBinary(int n)
{
     int i ;
     for (i=31; i>=0; i--)
          printf("%d", ((1<<i & n))?1:0) ;
     printf("\n") ;
}

/* Function to get 2's complement of a number */
int get2scomplement(int n)
{
     int i, k=0 ;
     for (i=0; i<32; i++)
          k |= ~(1<<i | n) ;
     k+=1 ;

     return k ;
}

No comments:

Post a Comment

Followers