Assaf
Assaf

Reputation: 1124

Binary number output in C

I have an assignment to write a program that converts decimal numbers to binary numbers, in the C programming language.

This is the code I wrote:

#include <stdio.h>
#define MAX_LEN 1000

void translate_dec_bin(char s[]){
    unsigned int decNum;
    sscanf_s(s, "%d", &decNum);

    while (decNum > 0){
        printf("%d", decNum % 2);
        decNum = decNum / 2;
    }
    printf("\n");
}

main(){
    char s[MAX_LEN];
    char c='\0';
    int count=0;
    printf("enter a nunber\n");
    while (c < MAX_LEN && ((c = getchar()) != EOF) && c != '\n'){
        s[count] = c;
        ++count;
    }
    translate_dec_bin(s);
}

However, when the input is 1, the output I get is 1 instead of 0001. In other words, I want the 0's to appear in my output. How can I do that?

Upvotes: 0

Views: 382

Answers (2)

Darth Hunterix
Darth Hunterix

Reputation: 1510

First, read mah's comment: although he suggest hitting a fly with a nuclear missile, he suggest you a right approach.

But in this case, your problem is simple: your loop in translate_dec_bin function finishes, because it has nothing left to do.

Think about for a second: your condition is "while decNum is greater than 0, print 1 or 0", right? I guess you know by now, that in C if you divide integer, the remainder is ommited, so 1/2=0.

Now look at your code: when you give argument "1", the loop iterates only once, so you get only one character in the output.

If you want more characters, you need more conditions. I leave it to you to come up with them, I'm not THAT reputation-hungry as mah suggested :)

And by the way: there is no way you can fit 1000 digits long number in an unsigned int, and that's what you're trying to do.

Upvotes: 1

UmNyobe
UmNyobe

Reputation: 22920

Assuming you already have computed your decimal number the basic idea without using print formating is the following:

char* list[] = {"0000", "000", "00", "0", ""};

char* leading_of(int num) {
   int v = 0;
   while(num > 0 && v < 4){
      num = num /10;
      v++;
   }
   return list[v];
}

printf("%s%d", leading_of(decNum), decNum);

If the number of characters or the padding character is variable you need to drop the list and do something more clever instead.

Upvotes: 0

Related Questions