Search code examples
cstringturbo-c

Adding integers as char to create a string in C


I wanted to ask if there is a way to add integers as char values and create a string. I have written some code but only last digit is detected

void binary(int decimal) {
  int modulus;
  char bin[9];
  while (decimal != 0) {
    modulus = decimal % 2;
    sprintf(bin, "%d", modulus);
    if (modulus == 1) {
      decimal--;
    }
    decimal = decimal / 2;
  }
  puts(bin);
}

If the decimal is 10 then the holds only 1 instead 0101. How can I fix it? I am using Turbo C++ 3.0.


Solution

  • This is exactly your function with slight modifications and comments.

    The binary string is still reversed though.

    void binary(int decimal) {
      int modulus;
      char bin[9];
      char temp[2];   // temporary string for sprintf
    
      bin[0] = 0;     // initially binary string set to "" (empty string)
    
      while (decimal != 0) {
        modulus = decimal % 2;
    
        sprintf(temp, "%d", modulus);  // print '1' or '0' to temporary string
        strcat(bin, temp);             // concatenate temporary string to bin
    
        if (modulus == 1) {
          decimal--;
        }
        decimal = decimal / 2;
      }
      puts(bin);
    }
    

    There are more efficient ways to achieve this, especially makeing use of the left shift operator (<<), that way you can construct the binary string directly without needing to reverse it at the end.