Converting decimal number to binary in C

前端 未结 4 1778
日久生厌
日久生厌 2021-01-17 03:22

I\'m trying to convert a decimal number to binary but I somehow end up getting \'random\' ASCII symbols as an output. Here is my program:

#include 

        
4条回答
  •  醉梦人生
    2021-01-17 04:01

    There are multiple problems with your code (no specific order but the one I found them):

    • You are initializing a char with an int at line binary[i] = number % 2; you should properly transform the integer to a character, like this:

      binary[i] = '0' + (number % 2);
      
    • You are writing printf("\n%s", binary); where binary is a char[10], thus not necessarily null-terminated. You should add one more character to binary and initialize it to \0:

      char binary[11];
      binary[10] = '\0';
      
    • You are wrongly initializing your array: you start with i = 50 and binary[10]. You should add a constant and use it twice:

      #define MAX_SIZE 32
      int i = MAX_SIZE - 1;
      char binary[MAX_SIZE + 1];
      binary[MAX_SIZE] = '\0';
      

      Note the -1 you forgot, that avoids that you write after the end of the string, and the +1 that is essentially the last problem

    • You are reading an int and trying to get its binary representation; but the (true) binary representation of a negative value is usually not what you would expect. Prefer reading an unsigned int:

      unsigned int number;
      scanf("%u", &number);
      
    • You could replace number % 2 with number & 1 and number /= 2 with number >>= 1; which is more representative of exactly what (binary) operations you are running on number. Besides, this should actually work correctly on negative integers, where your version should not (untested, anyway you usually have no reason of wanting to get the binary representation of a negative integer):

      binary[i--] = '0' + (number & 1);
      number >>= 1;
      
    • You stop after your number is zero, but that means you did not necessarily fill the binary array; this implies you may have uninitialized characters at the beginning of binary (on VC++ in debug mode this should IIRC be displayed as ÿ characters). You should add, after your loop, something such as this so as to fill the array:

      while (i >= 0)
          binary[i--] = '0';
      

    Hope that helps!

提交回复
热议问题