C 将整数转换为4位二进制

C 将整数转换为4位二进制,c,binary,C,Binary,我有下面的代码将一个整数转换为0到15之间每个整数的二进制表示形式,因此我需要一个整数的4位表示形式 代码运行正常,但问题是二进制文件的长度不正确,因此当给定1为int时,它返回1作为输出,而不是0001。 对于2,它应该返回0010,但相反,它返回10 如何更改此代码以使其返回正确的表示形式?打印结果时,可以使用printf%04d,但仅用于打印,因为实际值仍然不同 我试图让另一个方法获取一个整数,将其转换为字符串,然后根据其长度在其前面添加0,直到长度为4 #include <stdi

我有下面的代码将一个整数转换为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");
    }

初始化大小为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 |
,您的要求非常不明确,但从评论中我认为我已经收集到了您需要的内容。根据我的建议,您需要更改函数以返回字符串,而不是
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);
演示:

我的尝试

#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;
}
#包括
#包括
整数转换(整数-小数)
{
如果(dec==0)
{
//printf(“基本c\n”);
返回0;
}
其他的
{
//printf(“Rec call\n”);
返回(12月%2)+10*转换(12月/2);
}
}
int main()
{
int二进制=10;
二进制=转换(二进制);
printf(“%d”,二进制);
返回0;
}

谢谢,这正是我需要的,现在当我有数字1时,它返回0001,依此类推。我不知道为什么你们不能从我的问题中得到这个,我想我很清楚我想在这里发生什么。无论如何,再次感谢你,现在我可以进一步完成我的任务了。我接受你的回答。谢谢你,我是在Ajay Brahmakshatriya的帮助下做这件事的,他的回答几乎和你的一样。
#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;
}