7

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 (e.g. 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);
5
  • Integer overflow? long (if 64 bits) can only accomodate 10 digits. Commented Nov 2, 2012 at 18:31
  • 3
    I'd suggest using strings and concatenating your "0" and "1" characters. Depending on the size of your integers, you're going to overflow at fairly small values. Commented Nov 2, 2012 at 18:31
  • It is not a good idea to store binary in long int. Instead you can use strings. Following code should work for you. Commented Nov 2, 2012 at 18:33
  • 2
    You should really clear up your thinking. There is no such thing as a "decimal number" or a "binary number". The place-value system is just a way to represent numbers. Ask yourself: is the number of fingers on your hand a binary or a decimal? You can only program right if you're thinking straight. Commented Nov 2, 2012 at 18:38
  • Just a suggestion: I think this is the best method - string binary = bitset<50>(num).to_string(); where num is the decimal number and 50 is the number of binary digits you need. Commented May 5, 2016 at 16:27

7 Answers 7

4

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';
}
Sign up to request clarification or add additional context in comments.

5 Comments

The problem is I am not familiar with pointers in C yet, that's why I was trying to find a more beginner-friendly solution.
You should probably try to get familiar with pointers soon. They make up the core of C
@FlorinStingaciu: Will that work if number is having more than actual 5 bits.. I didn't get it plz explain
I have also submitted one answer ..could u plz see is that correct..the only problem there in my answer is to print the string in revere order
@Omkant if you really want to you could use this to reverse the string before you return it.
3

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;
}

Comments

2

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;

        }

Comments

0

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

Comments

0

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;
}

2 Comments

What is t in the second printf statement of main()?
@Question_Guy a typo!
0

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;  
}  

Comments

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.