converting Binary Numbers in to decimal numbers

前端 未结 6 667
情歌与酒
情歌与酒 2021-01-28 23:42

I need a program to convert Binary numbers into Decimal number in Java or in C++.

is there some one who can help me.

相关标签:
6条回答
  • 2021-01-29 00:22

    In C++, there are the library functions "strtol", "strtoull", etc. that take a string and the base to use for conversion. If you need more than 32 / 64 bits, then you can use the GMP library which is only limited by available memory.

    0 讨论(0)
  • 2021-01-29 00:25

    Use binary expansion. For example 1101 1001 is:

    (1 x 2^7) + (1 x 2^6) + (1 x 2^4) + (1 x 2^3) + (1 x 2^0)

    which is equal to:

    217 in decimal.

    Here is the algorithm:

    1.) Prompt the user for a binary number.

    2.) Store the number in an array. The first element i.e. anArray[0] should contain a value of 1, the second element should have a value of 0 . . .

    3.) Implement a for loop to do the calculation.

    0 讨论(0)
  • 2021-01-29 00:25

    Good C function itoa

    0 讨论(0)
  • 2021-01-29 00:29

    Algorithmically (in c/c++):

    const char* binary = "110010101011";
    int decimal = 0;
    
    while ( *binary ) 
    {
        decimal*=2;
        decimal+=*binary-'0';
        binary++ ;
     }
    

    Note that this doesn't handle invalid characters (anything other than binary digits).

    0 讨论(0)
  • 2021-01-29 00:37

    Java:

    String binary = "110010101011";
    int decimal = Integer.parseInt(binary, 2);
    

    C++:

    #include <cstdlib>
    const char* binary = "110010101011";
    int decimal = strtol(binary, NULL, 2);
    

    Here's the Javadoc page for Integer.parseInt and here's the manpage for strotol.

    0 讨论(0)
  • 2021-01-29 00:40

    Yes, I know how.

    Use:

    String input0 = "1010";
    String input1 = "10";
    
    int number0 = Integer.parseInt(input0, 2);
    int number1 = Integer.parseInt(input1, 2);
    
    int sum = number0 + number1;`
    
    0 讨论(0)
提交回复
热议问题