Wednesday, May 1, 2013

To find if the nth bit is set

Following from the previous example, this is to find if the nth bit is set or not. Of course, ensure  the second argument i.e. bit_pos is send correctly, have sufficient checks for that. Again, here the assumption is bit_pos starts from 0 to 31 for 32 bit integer.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdio.h"
#include "limits.h"

static unsigned short is_set(unsigned int x,
                        unsigned short bit_pos)
{
        return !!((1<<bit_pos) & x);
}


int main(int argc, char **argv)
{

        /* 0x1000 = 0000 0000 0000 0000 0001 0000 0000 0000
                                           |
                                          12th Bit
        */
        printf("0x%08x - %d \n", 0x1000, is_set(0x1000, 12));
        printf("0x%08x - %d \n", 0x1000, is_set(0x1000, 13));


        return 0;
}


[root@Imperfecto_1 ~]# gcc -g run.c && ./a.out
0x00001000 - 1
0x00001000 - 0

No comments:

Post a Comment