简体   繁体   中英

Decimal to binary algorithm in C

I am trying to use the following algorithm to convert a decimal number to a binary number in C. I don't understand why it doesn't work properly for some inputs (eg for 1993 I get 1420076519).

int aux=x;
long bin=0;
while (aux>0)
{
    bin=bin*10+aux%2;
    aux=aux/2;
}
printf("%d in decimal is %ld in binary.", x, bin);

When you print a long you dont print the binary. The best way to convert to binary or show the binary representation of a decimal number is by storing it in a string. Bellow is a solution offered in a another SO answer

void getBin(int num, char *str)
{
  *(str+5) = '\0';
  int mask = 0x10 << 1;
  while(mask >>= 1)
    *str++ = !!(mask & num) + '0';
}

If you know the algorithm there's no reason not to use itoa

http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/

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

int main ()
{
  int n;
  char output[100];

  printf("Enter a number: ");
  scanf("%d", &n);

  itoa(n, output, 2); //2 means base two, you can put any other number here

  printf("The number %d is %s in binary.", n, output);

  return 0;
}

How does the conversion works?

/* Example: 
   125(10) -----> ?(2)                     125  |_2
                                            -1-   62  |_2
                                                  -0-   31 |_2
                                                        -1-  15 |_2
                                                             -1-  7 |_2
                                                                 -1-  3 |_2
                                                                     -1-  1 */

So in this example the binary number for 125(10) is 1111101(2), and this is the process I describe in my function.

/* Functions declaration (Prototype) */

 int wordCalculator( int * const word, long int number, int base );
    int main( void )
        {
            int i, base;
            int word[ 32 ];
            unsigned long int number;

            printf( "Enter the decimal number to be converted: " );
            scanf( "%ld", &number );
            printf( "\nEnter the new base: " );
            scanf( "%d", &base );

            i = wordCalculator( word, number, base );

            printf( "The number is: " );

            for(; i >= 0; i--){

                if ( word[ i ] <= 9)
                    printf( "%d", word[ i ] );

                else
                    /* 65 represents A in ASCII code. */
                    printf( "%c", ( 65 - 10 + word[ i ] ) );
            }

            printf( "\n" );
        }

        int wordCalculator( int * const word, long int number, int base )
        {
            unsigned long int result = number;
            int i, difference;

            i = 0;
            do{
                difference = result % base;
                result /= base;
                *( word + i ) = difference;
                i++;

                if ( result < base )
                    *( word + i ) = result;

            } while( result >= base );

            return i;

        }

You should be using strings to store binary number. Following code should work for you.

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

char *decimal_to_binary(int);

main()
{
   int n, c, k;
   char *pointer;

   printf("Enter an integer in decimal number system\n");
   scanf("%d",&n);

   pointer = decimal_to_binary(n);
   printf("Binary string of %d is: %s\n", n, pointer);

   free(pointer);

   return 0;
}

char *decimal_to_binary(int n)
{
   int c, d, count;
   char *pointer;

   count = 0;
   pointer = (char*)malloc(32+1);

   if ( pointer == NULL )
      exit(EXIT_FAILURE);

   for ( c = 31 ; c >= 0 ; c-- )
   {
      d = n >> c;

      if ( d & 1 )
         *(pointer+count) = 1 + '0';
      else
         *(pointer+count) = 0 + '0';

      count++;
   }
   *(pointer+count) = '\0';

   return  pointer;
}

I think the shortest answer is

char* getBinary(int n,char *s)
{
  while(n>0)
  {
    *s=(n&1)+'0';
    s++;
    n>>=1;
  }
  *s='\0';
  return s;
}

In the called function print it in reverse way .. because storing is done LSB to MSB But we have to print MSB first then LSB

You can use the below algorithm to convert Decimal number to Binary number system .

#include <stdio.h>  

int main()  
{  
    long long decimal, tempDecimal, binary;  
    int rem, place = 1;  

    binary = 0;  

    /* 
     * Reads decimal number from user 
     */  
    printf("Enter any decimal number: ");  
    scanf("%lld", &decimal);  
    tempDecimal = decimal;  

    /* 
     * Converts the decimal number to binary number 
     */  
    while(tempDecimal!=0)  
    {  
        rem = tempDecimal % 2;  

        binary = (rem * place) + binary;  

        tempDecimal /= 2;  
        place *= 10;  
    }  

    printf("\nDecimal number = %lld\n", decimal);  
    printf("Binary number = %lld", binary);  

    return 0;  
}  

This is a recursive solution that i wrote, it is simple and works fine.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int  printBinary(int N)
{
    if(N < 0){errno = EINVAL; return -1;}

    if(N == 0)
        printf("0");
    else if(N == 1)
        printf("1");
    else
    {
        printBinary(N/2);
        printf("%d", N%2);
    }

    return 0;
}

int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        fprintf(stderr, "usage: %s NUM\nWhere NUM is an integer number\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    errno = 0;


    long NUM = strtol(argv[1], NULL, 10);
    if(NUM == 0 && errno != 0)
    {
        perror("Error during number acquisition: ");
        exit(EXIT_FAILURE);
    }

    if(NUM < 0)
    {
        printf("-");
        printBinary(-NUM);
    }
    else
        printBinary(NUM);

    printf("\n");

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM