Now for those who are not familiar with the concept of binary numbers, please read the following post : decimal to binary conversion.
Now, the method works like this. Just traverse the binary number step by step, starting from 0 to n-1, where n is the most significant bit(MSB) ,
multiply them with 2 with raising powers and add the sum together. E.g to convert 1000(which is binary equivalent of 8), just do the following
1 0 0 0 ==> going from right to left
0 x 2^0 = 0
0 x 2^1 = 0;
0 x 2^2 = 0;
1 x 2^3 = 8;
work. Note : The program works only for 16-bit binary numbers(non-floating) or less. Leave a comment if anything is not clear. You are bound to receive a reply.
// Program to convert binary to its decimal equivalent
int i=0,sum = 0;
// prompts the user to input a 16-bit binary number
std::cout<<" Enter the binary number (16-bit) : ";
while ( i != 16 ) // runs 16 times
sum += (x%10) * pow(2,i);
x = x/10;
std::cout<<"\n The decimal equivalent is : "<<sum;
------ OUTPUT ------
------ Programming Advice and Tips ------
1 : Note : The above program only accepts 16-bit binary numbers as inputs. This limit can be increased by increasing the number of loop executions by
changing the value in the while loop from 16 to say 32. (be sure it is a valid number which is a factor of 2 ).
2 : This program is the most basic method to do this type of conversion. However, there are a number of algorithms to do the same, so just GOOGLE out some
of them. Try it out, there are a variety of programs that do the same conversion in different ways.
Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.
2 : Decimal to binart conversion (v2.0) : http://programsplusplus.blogspot.in/2012/04/decimal-to-binary-conversion-program.html