tags:

views:

292

answers:

4

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

is there some one who can help me.

A: 

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.

Dietrich Epp
+1  A: 

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.

Brandon
Better written as1 << 7 | 1 << 6 | 1 << 4 | 1 << 3 | 1 << 0
Yann Ramin
a mathematical explanation is more understandable than code
fa.
+11  A: 

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.

zneak
A: 

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).

phord