开发者

converting Binary Numbers in to decimal numbers

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

is there some one who can help开发者_开发技巧 me.


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.


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.


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.


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;`


Good C function itoa


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜