Adding integers as char to create a string in C

202 views Asked by At

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.

3

There are 3 answers

6
Jabberwocky On BEST ANSWER

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.

0
Jean-François Fabre On

of course, you're printing on the same bin location, not moving your "cursor".

Declare a pointer on the string and increment it after each sprintf, should work, since sprintf issues only 1 digit + null-termination char.

char bin[9];
char *ptr = bin;
  while (decimal != 0) {
    modulus = decimal % 2;
    sprintf(ptr, "%d", modulus);
    ptr++;

that generates the string, but reversed (because lower bits are processed first). Just print it reversed or reverse it afterwards.

 int l = strlen(bin);
 for (i=0;i<l;i++)
 {
     putc(bin[l-i-1]);
 }
 putc("\n");
1
Hans Petter Taugbøl Kragset On

Here is a function that prints a decimal as binary:

void print_binary(int num)
{
    int pos = (sizeof(int) * 8) - 1;
    printf("%10d: ", num);

    for (int i = 0; i < (int)(sizeof(int) * 8); i++) {
        char c = num & (1 << pos) ? '1' : '0';
        putchar(c);
        if (!((i + 1) % 8))
            putchar(' ');
        pos--;
    }
    putchar('\n');
}

output:

        42: 00000000 00000000 00000000 00101010