C语言中的十进制转二进制算法

7

我正在尝试使用以下算法在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);

整数溢出?如果是64位的话,long只能容纳10个数字。 - John Dvorak
3
我建议使用字符串并连接你的 "0" 和 "1" 字符。根据你的整数大小,你会在相当小的值处溢出。 - Bob Kaufman
将二进制存储在长整型中并不是一个好主意。相反,您可以使用字符串。以下代码应该适用于您。 - CCoder
2
你应该理清思路。没有所谓的“十进制数”或“二进制数”。位值系统只是一种表示数字的方式。问问自己:手指的数量是二进制还是十进制?只有当你思路清晰时才能编写正确的程序。 - Kerrek SB
仅供参考:我认为这是最好的方法 - string binary = bitset<50>(num).to_string(); 其中 num 是十进制数,50 是所需二进制位数。 - user3576734
7个回答

4

当你打印一个长整型时,你不会打印二进制。将其转换为二进制或显示十进制数的二进制表示的最佳方式是将其存储在字符串中。下面是一个在另一个SO答案中提供的解决方案(链接)

void getBin(int num, char *str)
{
  *(str+5) = '\0';
  int mask = 0x10 << 1;
  while(mask >>= 1)
    *str++ = !!(mask & num) + '0';
}

问题在于我还不熟悉C语言中的指针,所以我正在尝试寻找更适合初学者的解决方案。 - Tudor Ciotlos
你应该尽快熟悉指针,因为它们构成了 C 语言的核心。 - Florin Stingaciu
@FlorinStingaciu:如果数字具有超过实际5位的位数,那么这是否有效?我不明白,请解释一下。 - Omkant
我也提交了一个答案..请问您能否看一下是否正确..我的答案中唯一的问题是以相反的顺序打印字符串。 - Omkant
@Omkant 如果你真的想要的话,你可以使用 这个 来在返回字符串之前将其反转。 - Florin Stingaciu

3
如果您知道算法,就没有理由不使用 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;
}

2

转化过程是如何运作的?

/* 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;

        }

0

你应该使用字符串来存储二进制数。下面的代码应该适用于你。

#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
@Question_Guy 打错字了! - CCoder

0

我想最简短的回答是:

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

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

0

您可以使用以下算法将十进制数转换为二进制数系统

#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;  
}  

0

这是我写的一个递归解决方案,它简单而且运行良好。

#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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接