4 Replies - 1928 Views - Last Post: 09 August 2011 - 10:03 AM Rate Topic: -----

#1 eXceed69   User is offline

  • "Super Sentai Knight Of DawN"
  • member icon

Reputation: 8
  • View blog
  • Posts: 688
  • Joined: 12-November 06

Decimal to Binary

Posted 05 December 2006 - 07:52 PM

Description: Convert a decimal (denary) integer to a binary string
//[email protected]

#include <stdio.h>
 
void dec2bin(long decimal, char *binary);
 
int main()
{
  long decimal;
  char binary[80];
 
  printf("nn Enter an integer value : ");
  scanf("%ld",&decimal);
  dec2bin(decimal,binary);
  printf("n The binary value of %ld is %s n",decimal,binary);
 
  getchar();  // trap enter 
  getchar();  // wait
  return 0;
}
 
//
// accepts a decimal integer and returns a binary coded string
//
void dec2bin(long decimal, char *binary)
{
  int  k = 0, n = 0;
  int  neg_flag = 0;
  int  remain;
  int  old_decimal;  // for test
  char temp[80];
 
  // take care of negative input
  if (decimal < 0)
  {      
    decimal = -decimal;
    neg_flag = 1;
  }
  do 
  {
    old_decimal = decimal;   // for test
    remain    = decimal % 2;
    // whittle down the decimal number
    decimal   = decimal / 2;
    // this is a test to show the action
    printf("%d/2 = %d  remainder = %dn", old_decimal, decimal, remain);
    // converts digit 0 or 1 to character '0' or '1'
    temp[k++] = remain + '0';
  } while (decimal > 0);
 
  if (neg_flag)
    temp[k++] = '-';       // add - sign
  else
    temp[k++] = ' ';       // space
 
  // reverse the spelling
  while (k >= 0)
    binary[n++] = temp[--k];
 
  binary[n-1] = 0;         // end with NULL
}


Is This A Good Question/Topic? 0
  • +

Replies To: Decimal to Binary

#2 20524587   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 07-July 09

Re: Decimal to Binary

Posted 14 July 2009 - 02:13 AM

I like the program very much
Was This Post Helpful? 0
  • +
  • -

#3 djrafid   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 22-November 09

Re: Decimal to Binary

Posted 22 November 2009 - 07:58 AM

too big for beginner but very efeective
Was This Post Helpful? 0
  • +
  • -

#4 mikejmae   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 10-January 10

Re: Decimal to Binary

Posted 18 January 2010 - 10:00 PM

plzzzzzzzzz nd ko makitaaaa
Was This Post Helpful? 0
  • +
  • -

#5 kambagiri   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 23-September 10

Re: Decimal to Binary

Posted 09 August 2011 - 10:03 AM

nice code man
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1