简体   繁体   English

Integer 到 C 中的二进制

[英]Integer to Binary in C

I am new to C programming and unsure what is wrong with my program.我是 C 编程的新手,不确定我的程序有什么问题。 I am writing a program which takes an integer as an input and returns it in binary form.我正在编写一个程序,它将 integer 作为输入并以二进制形式返回。

An input of 43 would output 101011, but the output is 1.输入 43 将是 output 101011,但 output 是 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;
}

With integer values a Right-Shift is equivalent to dividing by two.对于 integer 个值,右移相当于除以二。 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' .因此,您可以简单地通过右移并评估 memory 中的结果位是1还是0并输出适当的字符'1''0'来创建二进制表示。 A simple function for that would be:一个简单的 function 是:

/** 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:然后结合您的main()并添加输入验证,您可以执行以下操作:

#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) 注意:调用者负责换行控制。在某些情况下,您可能希望 output 在输出'\n'之前将数字的多个二进制表示放在一起,以便将任务留给调用者 function 来执行)

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...)您还可以将逻辑调整为 output 填充表示为 X 位数(4、8、16、32、64 等...)

Look things over and let me know if you have further questions.检查一下,如果您还有其他问题,请告诉我。

I am new to C programming and unsure what is wrong with my program.我是 C 编程的新手,不确定我的程序有什么问题。 I am writing a program which takes an integer as an input and returns it in binary form.我正在编写一个程序,它将 integer 作为输入并以二进制形式返回。

An input of 43 would output 101011, but the output is 1.输入 43 将 output 101011,但 output 为 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM