Monday, March 21, 2016

Bit Maipulations

Most hated area in programming. Anyways here you go few important examples.

1) given 32 bit integer, swap ith and jth positions
swap(int n,int i,int j)
{
    if( (n & 1<<i)>>i ^ (n & (i<<j))>>j) ) // if bits i and j are different
    {
        n^= 1<<i;
        n^= 1<<j;
    }
    return n;
}

2) check 9th bit ser or not
return (number & (position - 1 ) ;

3) To find the number of zeros in an integer
int zerocount(int n)
{
    int ctr  = 0 ;
    while (n>0) {
        ctr = ctr + !(n & 1 ) ;
        n = n << 1 ;
    }
    return ctr ;
}

4) ip string to integer
uint ip2int(char *str)
{
    uint x = 0 ;
    char *tok = strtok(str, ".") ;
    for (i=3; tok != NULL; i--) {
        ans |= atoi(tok) << (8*i)) ;
        tok = strtok(tok, ".") ;
    }
    return tok ;
}

5) MSB of a number
int IsMSB(int x)
{
    if (x & 0x8000)
        printf("msb = 1") ;
    else
        printf("msb = 0") ;
}

6) count bits
int count(uint x)
{
    int i ;
    while (x) {
        x = x & (x-1) ;
        i++ ;
    }
    return i ;
}

7) result = a?b:c
 result = !!a * b + !a * c;

8) #define mysize(x) ((char*) &x+1) - ((char*) &x)  ;

9) multiply by power of 2
n << 2 ;

10) set a bit
unsigned char a = a  | (1<<n) ;

11) clear a bit
unsigned char b = b & ~(1<<n) ;

12) toggle a bit
unsigned char c = c ^ (1<<n) ;

13) test a bit
unsigned d = c & (1<<n) ;

14) right most bit
uchar right = val & 0xff ;
uchar left = (val>8) & 8 ;

No comments:

Post a Comment