You are here:

C/binary in c

Advertisement


Question
Can you show me how to create a decimal to binary conversion program in C as basic as possible? Our teacher hasn't taught us anything, but he wants us to somehow do this.
Thank you

Answer
Dear Justin !

Ya of course thats possible with C , here im presenting you a simple program , hope it will meet your expectation


#include <stdio.h>

void dec2bin(long decimal, char *binary);

int main()
{
  long decimal;
  char binary[80];
  
  printf("\n\n Enter an integer value : ");
  scanf("%ld",&decimal);
  dec2bin(decimal,binary);
  printf("\n The binary value of %ld is %s \n",decimal,binary);

  getchar();
  return 0;
}


void dec2bin(long decimal, char *binary)
{
  int  k = 0, n = 0;
  int  neg_flag = 0;
  int  remain;
  int  old_decimal;
  char temp[80];


  if (decimal < 0)
  {
     decimal = -decimal;
     neg_flag = 1;
  }
  do
  {
     remain    = decimal % 2;
     decimal   = decimal / 2;
     temp[k++] = remain + '0';
  } while (decimal > 0);

  if (neg_flag)
     temp[k++] = '-';       // add - sign
  else
     temp[k++] = ' ';       // space


  while (k >= 0)
     binary[n++] = temp[--k];

  binary[n-1] = 0;
}

Thanks and Regards !
Prince M. Premnath

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise


I'm sure that I can solve any doubts in Turbo C ,Graphics Programing ,Mouse, Hardware Programming ,File System ,Interrupts, BIOS handling , TSR Programming , General Concepts in C Language, handling inline Assembly statements

Experience

Research over 6+ Years

Organizations
CG-VAK Softwares and Exports Limited

Education/Credentials
Masters in Computer Applications

©2012 About.com, a part of The New York Times Company. All rights reserved.