【问题标题】:Decimal to binary algorithm in CC中的十进制到二进制算法
【发布时间】:2012-10-23 10:55:22
【问题描述】:

我正在尝试使用以下算法在 C 中将十进制数转换为二进制数。我不明白为什么它对于某些输入不能正常工作(例如,对于 1993,我得到 1420076519)。

int aux=x;
long bin=0;
while (aux>0)
{
    bin=bin*10+aux%2;
    aux=aux/2;
}
printf("%d in decimal is %ld in binary.", x, bin);

【问题讨论】:

  • 整数溢出? long(如果是 64 位)只能容纳 10 位数字。
  • 我建议使用字符串并将“0”和“1”字符连接起来。根据整数的大小,您将在相当小的值处溢出。
  • 将二进制存储在 long int 中不是一个好主意。相反,您可以使用字符串。以下代码应该适合您。
  • 你真的应该理清思路了。没有“十进制数”或“二进制数”之类的东西。位值系统只是一种表示数字的方式。问问自己:你手上的手指数是二进制还是十进制?只有思路清晰,才能正确编程。
  • 只是一个建议:我认为这是最好的方法 - string binary = bitset<50>(num).to_string(); 其中num 是十进制数,50 是您需要的二进制数。

标签: c algorithm binary decimal


【解决方案1】:

当您打印 long 时,您不会打印二进制文件。转换为二进制或显示十进制数的二进制表示的最佳方法是将其存储在字符串中。 Bellow 是另一个 SO answer

中提供的解决方案
void getBin(int num, char *str)
{
  *(str+5) = '\0';
  int mask = 0x10 << 1;
  while(mask >>= 1)
    *str++ = !!(mask & num) + '0';
}

【讨论】:

  • 问题是我还不熟悉 C 中的指针,这就是为什么我试图找到一个对初学者更友好的解决方案。
  • 您应该尽快熟悉指针。它们构成了 C 的核心
  • @FlorinStingaciu:如果数字超过实际的 5 位,这会起作用吗.. 我没明白,请解释一下
  • 我也提交了一个答案..你能看看是正确的吗..我的答案中唯一的问题是按顺序打印字符串
  • @Omkant 如果你真的想要,你可以在返回之前使用this 来反转字符串。
【解决方案2】:

您应该使用字符串来存储二进制数。以下代码应该适合您。

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

char *decimal_to_binary(int);

main()
{
   int n, c, k;
   char *pointer;

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

   pointer = decimal_to_binary(n);
   printf("Binary string of %d is: %s\n", n, pointer);

   free(pointer);

   return 0;
}

char *decimal_to_binary(int n)
{
   int c, d, count;
   char *pointer;

   count = 0;
   pointer = (char*)malloc(32+1);

   if ( pointer == NULL )
      exit(EXIT_FAILURE);

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

      if ( d & 1 )
         *(pointer+count) = 1 + '0';
      else
         *(pointer+count) = 0 + '0';

      count++;
   }
   *(pointer+count) = '\0';

   return  pointer;
}

【讨论】:

  • main() 的第二个 printf 语句中的 t 是什么?
  • @Question_Guy 打错字了!
【解决方案3】:

我认为最短的答案是

char* getBinary(int n,char *s)
{
  while(n>0)
  {
    *s=(n&1)+'0';
    s++;
    n>>=1;
  }
  *s='\0';
  return s;
}

在被调用的函数中以相反的方式打印它..因为存储完成LSBMSB 但是我们必须先打印MSB,然后再打印LSB

【讨论】:

    【解决方案4】:

    转换是如何进行的?

    /* Example: 
       125(10) -----> ?(2)                     125  |_2
                                                -1-   62  |_2
                                                      -0-   31 |_2
                                                            -1-  15 |_2
                                                                 -1-  7 |_2
                                                                     -1-  3 |_2
                                                                         -1-  1 */
    

    所以在这个例子中,125(10) 的二进制数是 1111101(2),这就是我在函数中描述的过程。

    /* Functions declaration (Prototype) */
    
     int wordCalculator( int * const word, long int number, int base );
        int main( void )
            {
                int i, base;
                int word[ 32 ];
                unsigned long int number;
    
                printf( "Enter the decimal number to be converted: " );
                scanf( "%ld", &number );
                printf( "\nEnter the new base: " );
                scanf( "%d", &base );
    
                i = wordCalculator( word, number, base );
    
                printf( "The number is: " );
    
                for(; i >= 0; i--){
    
                    if ( word[ i ] <= 9)
                        printf( "%d", word[ i ] );
    
                    else
                        /* 65 represents A in ASCII code. */
                        printf( "%c", ( 65 - 10 + word[ i ] ) );
                }
    
                printf( "\n" );
            }
    
            int wordCalculator( int * const word, long int number, int base )
            {
                unsigned long int result = number;
                int i, difference;
    
                i = 0;
                do{
                    difference = result % base;
                    result /= base;
                    *( word + i ) = difference;
                    i++;
    
                    if ( result < base )
                        *( word + i ) = result;
    
                } while( result >= base );
    
                return i;
    
            }
    

    【讨论】:

      【解决方案5】:

      如果你知道算法,就没有理由不使用itoa

      http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/

      #include <stdio.h>
      #include <stdlib.h>
      
      int main ()
      {
        int n;
        char output[100];
      
        printf("Enter a number: ");
        scanf("%d", &n);
      
        itoa(n, output, 2); //2 means base two, you can put any other number here
      
        printf("The number %d is %s in binary.", n, output);
      
        return 0;
      }
      

      【讨论】:

        【解决方案6】:

        您可以使用下面的algorithm to convert Decimal number to Binary number system

        #include <stdio.h>  
        
        int main()  
        {  
            long long decimal, tempDecimal, binary;  
            int rem, place = 1;  
        
            binary = 0;  
        
            /* 
             * Reads decimal number from user 
             */  
            printf("Enter any decimal number: ");  
            scanf("%lld", &decimal);  
            tempDecimal = decimal;  
        
            /* 
             * Converts the decimal number to binary number 
             */  
            while(tempDecimal!=0)  
            {  
                rem = tempDecimal % 2;  
        
                binary = (rem * place) + binary;  
        
                tempDecimal /= 2;  
                place *= 10;  
            }  
        
            printf("\nDecimal number = %lld\n", decimal);  
            printf("Binary number = %lld", binary);  
        
            return 0;  
        }  
        

        【讨论】:

          【解决方案7】:

          这是我写的一个递归解决方案,它很简单而且效果很好。

          #include <stdio.h>
          #include <stdlib.h>
          #include <errno.h>
          
          int  printBinary(int N)
          {
              if(N < 0){errno = EINVAL; return -1;}
          
              if(N == 0)
                  printf("0");
              else if(N == 1)
                  printf("1");
              else
              {
                  printBinary(N/2);
                  printf("%d", N%2);
              }
          
              return 0;
          }
          
          int main(int argc, char* argv[])
          {
              if(argc < 2)
              {
                  fprintf(stderr, "usage: %s NUM\nWhere NUM is an integer number\n", argv[0]);
                  exit(EXIT_FAILURE);
              }
              errno = 0;
          
          
              long NUM = strtol(argv[1], NULL, 10);
              if(NUM == 0 && errno != 0)
              {
                  perror("Error during number acquisition: ");
                  exit(EXIT_FAILURE);
              }
          
              if(NUM < 0)
              {
                  printf("-");
                  printBinary(-NUM);
              }
              else
                  printBinary(NUM);
          
              printf("\n");
          
              return 0;
          }
          

          【讨论】:

            猜你喜欢
            • 2020-02-10
            • 2015-09-22
            • 2021-02-26
            • 1970-01-01
            • 1970-01-01
            • 2014-04-19
            • 2019-04-09
            • 2017-08-22
            相关资源
            最近更新 更多