A Developer's Diary

Jul 5, 2010

Integer to Binary Representation

Binary representation is a number written using base 2. Each digit can have only one of the two possible values (0 or 1) e.g. 255 is written as 00000000 00000000 00000000 11111111, 500 as 00000000 00000000 00000001 11110100 and 1024 as 00000000 00000000 00000100 00000000

The following program converts an entered integer to it's equivalent binary representation

#include <stdio.h>
#define SIZE 8*sizeof(int)

int int2bin(int, char*);
int print_bstr(const char*);
int error();

int main()
{
    int number;
    char bstr[SIZE];
    while(1){
        printf("\nEnter the number ");
        scanf("%d", &number) ? int2bin(number, bstr) : error();
        print_bstr(bstr);
    }
}

int int2bin(int num, char* bstr)
{
    int i;
    for(i = SIZE - 1; i >= 0 ; --i, num >>= 1)
    {
        bstr[i] = (0x1 & num) + '0';
    }

    bstr[SIZE] = '\0';
}

int print_bstr(const char* bstr)
{
    int i = 0;
    while(bstr[i])
    {
        putchar(bstr[i++]);
        if(i % 8 == 0  && bstr[i])
            putchar(' ');
    }
}

int error()
{
    printf("Error: non-numeric data entered. Exiting");
    exit(-1);
}


Program Output

No comments :

Post a Comment