C中的二进制整数 [英] Integer to Binary in C

查看:61
本文介绍了C中的二进制整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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.

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

An input of 43 would output 101011, but the output is 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;
}

推荐答案

对于整数值,右移等于被二除.因此,您可以简单地通过右移并评估内存中的结果位是 1 还是 0 并输出适当的字符('1')来创建二进制表示形式'0'.一个简单的功能是:

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

然后结合您的 main()并添加输入的验证,您可以执行以下操作:

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

(注意:,调用方负责换行控制.在某些情况下,您需要在输出'\ n'之前一起输出数字的几种二进制表示形式以便任务留给调用函数执行)

(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)

使用/输出示例

$ ./bin/binprn
enter x: 255
11111111

$ ./bin/binprn
enter x: 127
1111111

$ ./bin/binprn
enter x: 43690
1010101010101010

您还可以调整逻辑以将填充的表示形式输出为X个位数(4、8、16、32、64等)

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.

这篇关于C中的二进制整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆