0

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.

Antony Woods
  • 4,415
  • 3
  • 26
  • 47
UbadahJ
  • 46
  • 6
  • 1
    `sprintf(bin, "%d", modulus);` You always write from front. – BLUEPIXY Aug 30 '17 at 08:10
  • It's not trivial because it writes the digits reversed. I had posted an answer but it prints the binary string reversed, so no good. recursion or reverse the string afterwards should solve it. – Jean-François Fabre Aug 30 '17 at 08:12
  • And to not always write from the front, increment your pointer (`bin`) every time you write to it (but maintain a reference to the start of the string for the return). – Hans Petter Taugbøl Kragset Aug 30 '17 at 08:13
  • @Jean-FrançoisFabre The expected result of OP is reversed. E.g `0101` : `10` (base 10) – BLUEPIXY Aug 30 '17 at 08:15
  • I know that the answer would be reversed that is why I am taking result as a string and then reversing it to print as output. – UbadahJ Aug 30 '17 at 08:16
  • 1
    NB: You don't need to decrement an odd value before dividing. E.g. 5/2 in integer division is 2, as it rounds down – king_nak Aug 30 '17 at 08:20
  • BLUEPIXY's comment contains the answer. `sprintf` overrides the string, so you start anew in each iteration. You need to find a way to concatenate the strings – king_nak Aug 30 '17 at 08:23
  • @king_nak _overrides_ -> _overwrites_. – Jabberwocky Aug 30 '17 at 08:27

3 Answers3

0

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");
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

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
  • Isn't there anyway to create a string using integers? Your answer is what I wanted, ir is just that I wanted to learn what I have done wrong – UbadahJ Aug 30 '17 at 08:19
0

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.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • Thanks for your answer. I actually made the same code from following the advice from the comments. However your code confirmed my code. Thanks! – UbadahJ Aug 30 '17 at 08:34
  • doesn't that generate the number reversed? – Jean-François Fabre Aug 30 '17 at 08:36
  • @Jean-FrançoisFabre yes it does, read the second sentence of the answer. – Jabberwocky Aug 30 '17 at 08:37
  • ok, so I'm undeleting my answer, it's simpler because it's not using temporary & strcat. – Jean-François Fabre Aug 30 '17 at 08:41
  • You could remove the `temp` and `strcat`by using `sprintf(bin, "%s%d", bin, modulus)`. Then, to get the string in the correct order, just reverse the parameters: `sprintf(bin, "%d%s", modulus, bin)` – king_nak Aug 30 '17 at 08:48
  • 1
    @king_nak using `sprintf` to print a string into itself results definitely in undefined behaviour: https://stackoverflow.com/questions/1973572/can-the-input-and-output-strings-to-sprintf-be-the-same/ – Jabberwocky Aug 30 '17 at 09:06