【问题标题】:converting integer into 4 bit binary将整数转换为 4 位二进制
【发布时间】:2018-03-28 13:28:45
【问题描述】:

我有以下代码将整数转换为从 0 到 15 的每个整数的二进制表示,因此我需要整数的 4 位表示。

它的代码工作正常,但问题是二进制的长度不正确,所以当给定 1 作为 int 时,它返回 1 作为输出而不是 0001。 对于 2,它应该返回 0010,但它返回 10。

如何更改此代码以使其返回正确的表示形式?打印结果时使用 printf %04d 是可以的,但仅用于打印,因为实际值仍然不同。

我正在尝试另一种方法,将整数转换为字符串,然后根据其长度在其前添加 0,直到长度为 4。

#include <stdio.h>
#include <stdlib.h>

int convert(int dec)
{
    if (dec == 0)
    {
        //printf("Base c\n");
        return 0;
    }
    else
    {
        //printf("Rec call\n");
        return (dec % 2) + 10 * convert(dec / 2);
    }
}

int main(int argc, char *argv[]) 
{
    // argc is number of arguments given including a.out in command line
    // argv is a list of string containing command line arguments

    int v = atoi(argv[2]);
    printf("the number is:%d \n", v);


    int bin = 0;

    if(v >= 0 && v <= 15){
        printf("Correct input \n");
        bin = convert(v);
        printf("Binary is: %04d \n", bin);
        printf("Binary is: %d \n", bin);

    }
    else{
        printf("Inorrect input, number cant be accepted");
    }

我需要这个方法来做什么: 1.给定一个整数 2. 返回这个整数的 4 位表示,不确定它应该是 int 还是 string。 3. 例如 convert(2) 应该返回 0010,6 返回 110,我希望这个是 0110 等等。 convert 方法应该为我做到这一点。我希望我清楚我会发生什么。

这应该返回:

1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
and so on
15 1111

【问题讨论】:

    标签: c binary


    【解决方案1】:

    您的要求非常不清楚,但我想我从 cmets 中收集了您的要求。根据我的建议,您需要更改函数以返回字符串而不是int

    你需要传递一个参数来返回字符串。所以函数将是 -

    char * convert(int dec, char *output) {
        output[4] = '\0';
        output[3] = (dec & 1) + '0';
        output[2] = ((dec >> 1) & 1) + '0';
        output[1] = ((dec >> 2) & 1) + '0';
        output[0] = ((dec >> 3) & 1) + '0';
        return output;
    }
    

    这个函数可以作为

     char binary[5];
     convert(15, binary);
     printf("%s", binary);
    

    演示:Ideone

    【讨论】:

    • 谢谢,这正是我需要的,现在当我有数字 1 时它返回 0001 等等。我不知道为什么你们不能从我的问题中得到这个,我想我很清楚我想在这里发生什么。无论如何,再次感谢现在我可以进一步完成我的任务。我接受你的回答。
    【解决方案2】:

    初始化一个大小为5的字符数组,例如:char arr[5]并标记arr[4] ='\0',其余槽为0,然后将LSB存储到4th 1st 阵列插槽附近的阵列插槽和 MSB。使用%s 格式说明符打印它。

    最初的数组看起来像 |0|0|0|0|\0|。假设您的输入是 5 并且您收到的输出是(以 int 的形式)101,然后将输出插入数组看起来像|0|1|0|1|\0|

    【讨论】:

    • 谢谢,我在 Ajay Brahmakshatriya 的帮助下完成了这个,它的答案几乎和你的一样。
    【解决方案3】:

    我的尝试

    #include <stdio.h>
    #include <stdlib.h>
    
    
    
    int convert(int dec)
    {
        if (dec == 0)
        {
            //printf("Base c\n");
            return 0;
        }
        else
        {
            //printf("Rec call\n");
            return (dec % 2) + 10 * convert(dec / 2);
        }
    }
    int main()
    {
     int binary = 10;
     binary = convert(binary);
     printf("%d", binary);
     return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 2014-04-15
      • 2015-01-21
      • 2011-02-10
      相关资源
      最近更新 更多