Wednesday, May 1, 2013

Print bits in an Integer

How to print bits in an integer? There are many ways to do this, I mean logically. I have 2 functions here, one recursive and the other one using a loop.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "limits.h"

/* This function prints the bits in a recursive mode
 * It takes out the bits from right side i.e. 0, 1, 2
 * and prints, this being recursive will print the
 * output in reverse order which will be finally
 * the correct order
 */
static void recurse_bits(int x, int *size)
{
        int bit = x & 0x1;
        if((*size)--){
                recurse_bits(x>>=1, size);
                printf("%d ", bit);
        }
}

/* This function prints the bit by taking it from the left
 * side, i.e. 31, 30 etc and printing it right away
 */
static void print_bits(unsigned int x, int *size)
{
        unsigned short bits = *size;
        unsigned int mask = 0x1 << (bits-1);
        while(bits--){
                printf("%d ", !!(x & mask));
                x<<=1;
        }
        return;
}

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

        int size = sizeof(unsigned int) * CHAR_BIT;
        int val = 9;

        print_bits(val, &size);
        printf("\n");

        recurse_bits(val, &size);
        printf("\n");

        return 0;
}


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

No comments:

Post a Comment