繁体   English   中英

C中的十进制到二进制算法

[英]Decimal to binary algorithm in C

我试图使用以下算法将十进制数转换为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);

当你打印很长时间你不打印二进制文件。 转换为二进制或显示十进制数的二进制表示的最佳方法是将其存储在字符串中。 贝娄是另一个SO 答案提供的解决方案

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

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

转换如何运作?

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

        }

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

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

我认为最简短的答案是

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

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

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

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

这是我写的一个递归解决方案,它很简单,工作正常。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM