【问题标题】:Integer to Binary in CC中的整数到二进制
【发布时间】:2020-12-11 12:43:12
【问题描述】:

我是 C 编程新手,不确定我的程序有什么问题。我正在编写一个程序,它将整数作为输入并以二进制形式返回。

输入 43 将输出 101011,但输出为 1。

请指教。

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

【问题讨论】:

  • 最明显的问题是output是一个单个字符的数组,也就是空字节。这意味着您没有空间在其中存储其他任何东西。 strncat 调用写入超出数组末尾,导致未定义的行为。
  • 打开编译器警告!
  • strncat 需要一个字符串,而不是一个字符。

标签: c binary converters


【解决方案1】:

对于整数值,右移相当于除以二。因此,您可以通过右移并评估内存中的结果位是10 并输出适当的字符('1''0')来创建二进制表示。一个简单的函数是:

/** 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' */
}

然后结合您的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 */
}

(注意:调用者负责换行控制。在某些情况下,您可能希望在输出 '\n' 之前一起输出多个二进制表示的数字,以便将任务留给调用执行的功能)

使用/输出示例

$ ./bin/binprn
enter x: 255
11111111

$ ./bin/binprn
enter x: 127
1111111

$ ./bin/binprn
enter x: 43690
1010101010101010

您还可以调整逻辑以将填充表示输出到 X 位数(4、8、16、32、64 等...)

检查一下,如果您还有其他问题,请告诉我。

【讨论】:

    猜你喜欢
    • 2017-08-22
    • 2021-12-28
    • 1970-01-01
    • 2021-01-27
    • 2015-04-30
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多