谈到使用C的二进制重新presentation整数? [英] Turning an integer to its binary representation using C?

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

问题描述

我还是个初学者编码,所以我有这个问题
我想一个整数转换成二进制其重新presentation

I'm still a beginner in coding so I had this problem I'm trying to convert an integer into its binary representation

 #include <stdio.h>
 int main () {
   int x;
   printf("input the number\n");
   scanf("%d",&x);

   while(x!=0) {
     if (x%2)
       printf("1");
     else
       printf("0");
   }
   return 0;
 }

因此​​,它输出这样12 = 0011,但12 = 1100
这是什么问题,如何解决呢?

So it outputs like this 12=0011 but 12=1100 What is the problem and how do I solve it?

推荐答案

程序逻辑的操作是错误的,试试这个

The Program Logic for the operation is wrong , try this

#include <stdio.h>
int main()
{
    int n, c, k;

    printf("Enter an integer in decimal number system\n");
    scanf("%d", &n);
    printf("%d in binary number system is:\n", n);

    for (c = 31; c >= 0; c--)
    {
        k = n >> c;

        if (k & 1)
            printf("1");
        else
            printf("0");
        }

        printf("\n");
    } 
    return 0;
}

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

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