Integer To Binary Converter

Integer To Binary Converter

I am interesting about how we can convert a integer number to binary number. So, I am try to create Integer To Binary Converter with C source Code.I am create this code from tutorial at http://www.helpwithpcs.com/courses/binary-numbers.htm.

Please look Integer To Binary source code below :

/*
 * iolibrary.c
 *
 *  Created on: Feb 9, 2012
 *      Author: toto
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

void int2binary(int inumber, char *binnumber, int lenbuffer);
int main(int argc, char **argv)
{
  int inumber;
  char *binnumber;
  int nbuffer;
  
  sscanf(argv[1], "%i", &inumber);
  sscanf(argv[2], "%i", &nbuffer);
  
  binnumber = (char*) calloc(nbuffer, sizeof(char));
  int2binary(inumber, binnumber, nbuffer);
  
  printf("Input = %i --> binary number = %s \n", inumber, binnumber);
  free(binnumber);
  return(1);
}

/* convert integer to binary number */
void int2binary(int inumber, char *binnumber, int lenbuffer)
{
  int iremainder, iresidue;
  char *tmp;
  
  memset(binnumber, 0, lenbuffer*sizeof(char));  //initialization binary output
  tmp = (char*) calloc(lenbuffer, sizeof(char));
  
  while(true) //loop until number=0
  {
    memset(tmp, 0, lenbuffer*sizeof(char));
    iremainder = inumber%2; //get Remainder after division with 2
    
    iresidue = (inumber-iremainder) / 2; //update residue after division with 2
    
    inumber = iresidue; //update input number with
    
    sprintf(tmp,"%i%s", iremainder, binnumber);
    sprintf(binnumber,"%s",tmp);
    
    if(inumber == 0)  //exit loop if dont number=0
        break;
  }
  free(tmp);
}

Save this Integer to Binary converter source code with name cbinary_converter.c. Compile with command :

gcc cbinary_converter.c -o cbinary_converter

We can running this Integer to Binary converter code with command :

./cbinary_converter integer_number buffer_alloc_length

buffer_alloc_length is maximum buffer allocation for create binary number. This number must be bigger than output binary number character.

Example Output:

toto@toto-laptop:~/Documents$ ./cbinary_converter 78 100
Input = 78 --> binary number = 1001110 
toto@toto-laptop:~/Documents$ ./cbinary_converter 789 100
Input = 789 --> binary number = 1100010101

Add a Comment

Your email address will not be published. Required fields are marked *