Integer to Binary in C

情到浓时终转凉″ 提交于 2021-01-24 10:53:05

问题


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;
}

回答1:


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.




回答2:


Your code has some errors and some mistakes, for the errors:

char output[] = "";

has the space for one character only, if you want to `store the binary in it you must make it large enough:

char output[64] = "";

These variables:

char binary1 = '1';
char binary2 = '0';

can't be used in strcat, this function takes strings as arguments, not characters, you'd need:

char* binary1 = "1";
char* binary2 = "0";

and in strcat:

strncat(output, binary1, 1);

This would fix the errors but not the mistakes, your cycle is not correct:

while(input != 0){
    if(input%2 != 0){
        input = input - 1; //this would change the value
        strncat(output, &binary1, 1);
    }
    else{
        input /= 2; //this must be performed regardless
        strncat(output, &binary2, 1);
    }
}

Corrected code:

while (input != 0)
{
    if (input % 2 != 0)
    {
        strncat(output, binary1, 1); //if it's 1
    }
    else
    {
        strncat(output, binary2, 1); //if it's 0
    }
    input /= 2; //always perform division
}

The code is still not very robust, input checks and interger overlfow and underflow checks are not performed, my advice is for you to use fgets to get input and stroll to parse the inputed string.

Using bitshift and the bitwise and like @David shows in his answer would be my advice, but if it's too complicated the above is acceptable.



来源:https://stackoverflow.com/questions/63534546/integer-to-binary-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!