将整数转换为4位二进制

时间:2018-03-28 13:28:45

标签: c binary

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

它运行良好的代码,但问题是二进制文件的长度不正确,所以当1为int时,它返回1作为输出而不是0001。 对于2它应该返回0010但是它返回10。

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

我试图创建另一个获取整数的方法将其转换为字符串然后根据其长度在它之前添加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");
    }

我需要这种方法: 给定一个整数 2.返回此整数的4位表示,不确定它应该是int还是字符串。 3.例如convert(2)应返回0010,6返回110,我希望这是0110,依此类推。转换方法应该是为我做的。我希望我清楚我将要发生什么。

这应该返回:

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

3 个答案:

答案 0 :(得分:2)

您的要求非常不明确,但从评论中我认为我收集了您的要求。根据我的建议,您需要更改函数以返回字符串而不是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 :(得分:1)

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

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

答案 2 :(得分:0)

my attempt 


=================================
#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;
}
相关问题