【问题标题】:Convert decimal to binary in C在C中将十进制转换为二进制
【发布时间】:2012-12-26 03:55:21
【问题描述】:

我正在尝试将十进制转换为二进制,例如 192 到 11000000。我只需要一些简单的代码来执行此操作,但我目前的代码不起作用:

void dectobin(int value, char* output)
{
    int i;
    output[5] = '\0';
    for (i = 4; i >= 0; --i, value >>= 1)
    {
        output[i] = (value & 1) + '0';
    }
}

任何帮助将不胜感激!

【问题讨论】:

  • youtu.be/1MJ1o56x-g8 - 这解释了您问题的全部解决方案。
  • 这里没有小数点。 value 已经是二进制的了。

标签: c binary decimal


【解决方案1】:

该值不是十进制的。计算机内存中的所有值都是二进制的。

您要做的是使用特定的基数将 int 转换为字符串。 有一个函数,它叫做itoahttp://www.cplusplus.com/reference/cstdlib/itoa/

【讨论】:

  • 和函数 sprintf 和 sscanf
  • @holmium 他们通常不支持base-2。另一方面,itoa 也是非标准的(但比printf("%b" 更常见
  • 十进制是表示 Base10 数字的另一种方式。我相信作者试图说明如何将 Base10 数字转换为 Base2 数字(无论内部表示如何)。
【解决方案2】:

首先192不能用4位表示

192 = 1100 0000 至少需要 8 位。

这是一个简单的C program to convert Decimal number system to Binary number system

#include <stdio.h>  
#include <string.h>  

int main()  
{  
    long decimal, tempDecimal;  
    char binary[65];  
    int index = 0;  

    /* 
     * Reads decimal number from user 
     */  
    printf("Enter any decimal value : ");  
    scanf("%ld", &decimal);  

    /* Copies decimal value to temp variable */  
    tempDecimal = decimal;  

    while(tempDecimal!=0)  
    {  
        /* Finds decimal%2 and adds to the binary value */  
        binary[index] = (tempDecimal % 2) + '0';  

        tempDecimal /= 2;  
        index++;  
    }  
    binary[index] = '\0';  

    /* Reverse the binary value found */  
    strrev(binary);  

    printf("\nDecimal value = %ld\n", decimal);  
    printf("Binary value of decimal = %s", binary);  

    return 0;  
} 

【讨论】:

  • strrev 不是 C 标准的一部分。
【解决方案3】:

对于您的示例 (192),5 位数字是不够的。可能你应该增加output

【讨论】:

    【解决方案4】:

    几天前,我正在寻找快速且便携的方法sprintf("%d", num)。在页面itoa with GCC找到了这个实现:

    /**
     * C++ version 0.4 char* style "itoa":
     * Written by Lukás Chmela
     * Released under GPLv3.
    
     */
    char* itoa(int value, char* result, int base) {
        // check that the base if valid
        if (base < 2 || base > 36) { *result = '\0'; return result; }
    
        char* ptr = result, *ptr1 = result, tmp_char;
        int tmp_value;
    
        do {
            tmp_value = value;
            value /= base;
            *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
        } while ( value );
    
        // Apply negative sign
        if (tmp_value < 0) *ptr++ = '-';
        *ptr-- = '\0';
        while(ptr1 < ptr) {
            tmp_char = *ptr;
            *ptr--= *ptr1;
            *ptr1++ = tmp_char;
        }
        return result;
    }
    

    【讨论】:

    • 哇,从中间索引回文数组的好技巧。
    【解决方案5】:

    十进制转二进制的算法

    • 将输入的十进制数除以 2 并存储余数。
    • 将商存储回输入数字变量。
    • 重复此过程,直到商变为零。
    • 等价的二进制数将是上述过程中的余数 倒序。

    你可以在这里查看c程序http://www.techcrashcourse.com/2015/08/c-program-to-convert-decimal-number-binary.html

    【讨论】:

      【解决方案6】:

      看起来像这样,但要小心,你必须反转生成的字符串:-)

      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      char output[256]="";
      
      int main()
      {
      int x= 192;
      int n;
      n = x;
      int r;
      do {
      r = n % 2;
      if (r == 1)
         strcat(output,"1");
      else strcat(output,"0");
      n = n / 2;
      }
      while (n > 0);
      
      printf("%s\n",output);
      }
      

      【讨论】:

        【解决方案7】:

        那么...您是否检查了代码的输出以了解它为什么不起作用?

        So iteration 1 of your loop:
        value = 192
        i = 4
        output[i] = (11000000 & 1) + '0' = 0 + 48 = 48 (char `0`)
        
        Iteration 2 of your loop:
        value = 96
        i = 3
        output[i] = (1100000 & 1) + '0' = 0 + 48 = 48 (char `0`)
        
        Iteration 3 of your loop:
        value = 48
        i = 2
        output[i] = (110000 & 1) + '0' = 0 + 48 = 48 (char `0`)
        
        Iteration 4 of your loop:
        value = 24
        i = 1
        output[i] = (11000 & 1) + '0' = 0 + 48 = 48 (char `0`)
        
        Iteration 5 of your loop:
        value = 12
        i = 0
        output[i] = (1100 & 1) + '0' = 0 + 48 = 48 (char `0`)
        
        Final string: "00000"  and you wanted: "11000000"
        

        您的代码有什么问题吗?没有。我也没有,你只是还不够远。将您的输出/循环更改为:

        output[8] = '\0';
        for (i = 7; i >= 0; --i, value >>= 1)
        

        然后你就会得到正确的结果。

        我只推荐一种更通用的方法,您使用的是固定长度的字符串,这将您限制为一定长度的二进制数。您可能想要执行以下操作:

        loop while number dividing down is > 0
        count number of times we loop
        malloc an array the correct length and be returned
        

        【讨论】:

          【解决方案8】:
          #include <stdio.h>
          #include <stdlib.h>
          void bin(int num) {
              int n = num;
              char *s = malloc(sizeof(int) * 8);
              int i, c = 0;
              printf("%d\n", num);
          
              for (i = sizeof(int) * 8 - 1; i >= 0; i--) {
                  n = num >> i;
                  *(s + c) = (n & 1) ? '1' : '0';
                  c++;
              }
              *(s + c) = NULL;
              printf("%s", s); // or you can also return the string s and then free it whenever needed
          }
          
          int main(int argc, char *argv[]) {
              bin(atoi(argv[1]));
              return EXIT_SUCCESS;
          }
          

          【讨论】:

            【解决方案9】:

            你也可以在函数下使用 while 循环来做到这一点。我只是在寻找我的解决方案,但我得到的解决方案不合适,所以我已经按照实际方法完成了它(使用 2 直到得到 0 并将提醒存储在一个数组中)并打印数组的反向和 @ 987654321@

            #include <stdio.h>
            
                int main()
                {
                    long long int a,c;
                    int i=0,count=0;
                    char bol[10000];
                    scanf("%lld", &a);
                    c = a;
                    while(a!=0)
                    {
                        bol[i] = a%2;
                        a = a / 2;
                        count++;
                        i++;
                    }
                    if(c==0)
                    {
                        printf("0");
                    }
                    else
                    {
                        for(i=count-1; i>=0; i--)
                        {
                            printf("%d", bol[i]);
                        }
                    }
                    printf("\n");
                    return 0;
                }
            

            【讨论】:

              【解决方案10】:

              //使用堆栈将十进制转换为二进制的C程序

              #include<stdio.h>
              
              #define max 100
              
              int stack[max],top=-1,i,x;  
              
              
              void push (int x)
              {
                ++top;
                stack [top] = x;
              }
              
              int pop ()
              { 
                 return stack[top];
              }   
              
              
              void  main()
              {
                int num, total = 0,item;
                print f( "Please enter a decimal: ");
                scanf("%d",&num);
                while(num > 0)
                {  
                  total = num % 2;
                  push(total);
                  num /= 2;
                }
              
              
              
               for(i=top;top>-1;top--)
               {     
                   item = pop ();
                   print f("%d",item);
               }
              
               }
              

              【讨论】:

                【解决方案11】:

                C 语言中将十进制转换为二进制

                #include<stdio.h>
                void main()
                {
                    long int n,n1,m=1,rem,ans=0;
                    printf("\nEnter Your Decimal No (between 0 to 1023) :: ");
                    scanf("%ld",&n);
                
                    n1=n;
                    while(n>0)
                    {
                        rem=n%2;
                        ans=(rem*m)+ans;
                        n=n/2;
                        m=m*10;
                    }
                
                    printf("\nYour Decimal No is   :: %ld",n1);
                    printf("\nConvert into Binary No is :: %ld",ans);
                }
                

                【讨论】:

                  【解决方案12】:

                  这是最简单的方法

                  #include <stdio.h>
                  
                  void main()
                  {
                      int n,i,j,sum=0;
                      printf("Enter a Decimal number to convert it to binary : ");
                      scanf("%d",&n);
                      for(i=n,j=1;i>=1;j*=10,i/=2)
                          sum+=(i%2)*j;
                      printf("\n%d",sum);
                  }
                  

                  【讨论】:

                    【解决方案13】:

                    这是一个将数字从十进制转换为二进制的简单程序

                    #include <stdio.h>
                    #include <conio.h>
                    void decToBinary(int);
                    
                    int main()
                    {
                        int number;
                    
                        printf("Enter number to convert to binary: ");
                        scanf("%d", &number);
                        
                        decToBinary(number);
                      return 0;
                    }
                    
                    void decToBinary(int num)
                    {
                        if (num == 0)
                        {
                            return ;
                        }
                    
                        decToBinary(num / 2);
                        printf("%d", num % 2);
                    }
                    

                    程序的输出:

                    【讨论】:

                      【解决方案14】:

                      也许理解算法可以让您编写或修改自己的代码以满足您的需要。我确实看到您没有足够的 char 数组长度来显示 192 的二进制值(您需要 8 位二进制,但您的代码只给出 5 位二进制)

                      这是一个page,它清楚地解释了算法。

                      我不是 C/C++ 程序员,所以这是我基于算法示例的 C# 代码贡献。

                      int I = 0;
                      int Q = 95;
                      string B = "";
                      while (Q != 0)
                      {
                          Debug.Print(I.ToString());
                          B += (Q%2);
                          Q = Q/2;
                          Debug.Print(Q.ToString());
                          I++;
                      }
                      
                      Debug.Print(B);
                      

                      所有的 Debug.Print 只是为了显示输出。

                      【讨论】:

                      • 所有的反对票是怎么回事?我确实回答了这个问题,但没有在 C 中回答。该算法很简单,可以自己在 C 中实现。
                      【解决方案15】:
                      //decimal to binary converter
                      long int dec2bin(unsigned int decimal_number){
                        if (decimal_number == 0)
                          return 0;
                        else
                          return ((decimal_number%2) + 10 * dec2bin(decimal_number/2));
                      }
                      

                      【讨论】:

                      • 感谢您提供此代码 sn-p,它可能会提供一些有限的短期帮助。一个正确的解释would greatly improve 它的长期价值通过展示为什么这是一个很好的解决问题的方法,并将使它对未来有其他类似问题的读者更有用。请edit您的回答添加一些解释,包括您所做的假设。例如,您如何解决这里的溢出问题?
                      【解决方案16】:
                      number=215
                      a=str(int(number//128>=1))+str(int(number%128>=64))+
                      str(int(((number%128)%64)>=32))+str(int((((number%12
                      8)%64)%32)>=16))+str(int(((((number%128)%64)%32)%16)>=8))
                      +str(int(((((((number%128)%64)%32)%16)%8)>=4)))
                      +str(int(((((((((number%128)%64)%32)%16)%8)%4)>=2))))
                      +str(int(((((((((((number%128)%64)%32)%16)%8)%4)%2)>=1)))))
                      print(a)
                      

                      您还可以使用“if”、“else”语句来编写此代码。

                      【讨论】:

                        【解决方案17】:
                        int main() 
                        { 
                         int n, c, k;
                         printf("Enter an integer in decimal number system: ");
                         scanf("%d", &n);
                         printf("%d in binary number system is: ", n);
                         for (c = n; c > 0; c = c/2) 
                          {
                           k = c % 2;//To
                           k = (k > 0) ? printf("1") : printf("0");
                          }
                         getch();
                         return 0; 
                        }
                        

                        【讨论】:

                          猜你喜欢
                          • 1970-01-01
                          • 2019-03-24
                          • 2019-04-26
                          • 2012-06-26
                          • 1970-01-01
                          • 2020-09-10
                          • 2021-12-26
                          • 2020-10-27
                          相关资源
                          最近更新 更多