Nathan King
Nathan King

Reputation: 21

Integer to Binary in C

I am new to C programming and unsure what is wrong with my program. I am writing a program which takes an integer as an input and returns it in binary form.

An input of 43 would output 101011, but the output is 1.

Please advise.

#include <stdio.h>
#include <string.h>

void printBinaryForm( int X )
//Purpose: Print parameter X in binary form
//Output: Binary representation of X directly printed
//Assumption: X is non-negative (i.e. >= 0)
{

    //[TODO] CHANGE this to your solution.
    
    int input = X;
    char output[] = "";
    char binary1 = '1';
    char binary2 = '0';
    
    while(input != 0){
        if(input%2 != 0){
            input = input - 1;
            strncat(output, &binary1, 1);
        }
        else{
            input /= 2;
            strncat(output, &binary2, 1);
        }
    }
       
    printf("%s",output);

}

int main(void)
{
    int X;  

    printf("Enter X: ");
    scanf("%d",&X);

    //print X in binary form
    printBinaryForm( X );

    return 0;
}

Upvotes: 1

Views: 485

Answers (1)

David C. Rankin
David C. Rankin

Reputation: 84561

With integer values a Right-Shift is equivalent to dividing by two. So you can create your binary representation simply by shifting right and evaluating whether the resulting bit in memory is 1 or 0 and outputting the appropriate character, either '1' or '0'. A simple function for that would be:

/** unpadded binary representation of 'v'. */
void binprn (const unsigned long v)
{
    if (!v) {
        putchar ('0');
        return;
    };

    size_t sz = sizeof v * CHAR_BIT;            /* get total bits in type */
    unsigned long rem = 0;

    while (sz--)                                /* loop sz number of times */
        if ((rem = v >> sz))                    /* while digits remain */
            putchar ((rem & 1) ? '1' : '0');    /* output '1' or '0' */
    
    /* note: the caller is responsible for adding the '\n' */
}

Then combining with your main() and adding validation of the input, you could do:

#include <stdio.h>
#include <limits.h>

/** unpadded binary representation of 'v'. */
void binprn (const unsigned long v)
{
    if (!v) {
        putchar ('0');
        return;
    };

    size_t sz = sizeof v * CHAR_BIT;            /* get total bits in type */
    unsigned long rem = 0;

    while (sz--)                                /* loop sz number of times */
        if ((rem = v >> sz))                    /* while digits remain */
            putchar ((rem & 1) ? '1' : '0');    /* output '1' or '0' */
    
    /* note: the caller is responsible for adding the '\n' */
}

int main (void) {
    
    int x;
    
    fputs ("enter x: ", stdout);                /* prompt for integer */
    if (scanf ("%d", &x) != 1) {                /* read/validate user-input */
        fputs ("error: invalid integer.\n", stderr);
        return 1;
    }
    
    binprn (x);             /* output binary represntation of x */
    putchar ('\n');         /* tidy up with newline */
}

(note: the caller is responsible for newline control. There may be cases where you want to output several binary representations of numbers together before outputting the '\n' so that task is left for the calling function to carry out)

Example Use/Output

$ ./bin/binprn
enter x: 255
11111111

or

$ ./bin/binprn
enter x: 127
1111111

or

$ ./bin/binprn
enter x: 43690
1010101010101010

You can also adjust the logic to output a padded representation to X number of bits (4, 8, 16, 32, 64, etc...)

Look things over and let me know if you have further questions.

Upvotes: 1

Related Questions