Thursday, 22 January 2015

C Programming - Integer to Binary

Convert an integer to binary irrespective of platform. The size of an integer varies from platform to platform. We assume the size of an integer either 32 bit or 64 bits in an application with respect to the working platform which leads to unexpected output.

The ideal solution is converting without assuming the size of an integer.
Don't forget to include the standard library stdlib.h which supports malloc and free functions. Else you will get a warning incompatible implicit declaration of built-in function 'malloc'.
#include <stdio.h>
#include <stdlib.h>
 
//function declaration
char *integer2binary(int n);
 
int main()
{
 
    //find how many bits are needed for the integer type.
    //sizeof() returns in bytes. So convert into bits.
    printf("Your integers are %u bits wide.\n\n", sizeof(int)*8);
 
    //An Array with integers
    int nums[13] = { 0, 1, 2, 3, -1, -2, -3, 255, 256, 1023, 1024, 8191, 8192 };
    int index;
 
    for (index = 0; index < 13; index++) {
 
        //A character pointer which stores the converted binary number
        char *s = integer2binary(nums[index]);
 
        //Printing the binary number
        printf("%d -> %s\n", nums[index], s);
 
        //Free the memory for the next conversion
        free(s);
    }
    return 0;
} 
 

char *integer2binary(int n) -


char *integer2binary(int n) {
 
    // determine the number of bits needed ("sizeof" returns bytes)
    int nbits = sizeof(n) * 8;
 
    //malloc function is used to allocate a certain amount of memory
    char *s = malloc(nbits+1);  // +1 for '' terminator
 
    s[nbits] = '';
 
    // forcing evaluation as an unsigned value prevents complications
    // with negative numbers at the left-most bit
    unsigned int u = *(unsigned int*)&n;
 
    //declaring a temporary variable
    int temp; 
 
    //left shift operator (<<)
    unsigned int mask = 1 << (nbits-1); // fill in values right-to-left
 
    for (temp = 0; temp < nbits; temp++)
    {
            s[temp] = ((u & mask) != 0) + '0';
 
            //right shift operator (>>)   
            mask >>= 1;
    }
    return s;
} 
   

Output -

integer to binary  
Your result may not be same as in the screenshot shown here. Depends on number of bits wide of integer on your machine.
 

Please share your thoughts on this post in the comments section.

Karthik Byggari

Author & Editor

Computer Science graduate, Techie, Founder of logicallyproven, Love to Share and Read About pprogramming related things.

1 comments:

 
biz.