Sunday, July 12, 2009

How to convert binary form to decimal in C++? (visual studio 2005)?

for example when i key in 00010001


the result will be 17.





can someone give me the code to do this C++ program

How to convert binary form to decimal in C++? (visual studio 2005)?
you can use a structure which contains the 'data' and a 'flag'


take the digits one by one and every time increase the counter. at the end of the scanning. the first objects data ( 1 or 0 ) should be multiplied by 2, counter-1 times. and add all of them. You will reach the result.
Reply:#include "stdafx.h"


#include %26lt;windows.h%26gt;


#include %26lt;iostream.h%26gt;





int toPower2(int value){


int rtnvle = 1;


if(value %26gt; 1)


for(int i=2;i%26lt;=value;i++){


rtnvle *= 2;


}


return rtnvle;


}





int main(int argc, char* argv[])


{


char binary_value[16];


int decimal = 0;





cout%26lt;%26lt;"Type in a binary value 16 max(remember binary is right to left): ";


cin%26gt;%26gt;binary_value;





for(int i=strlen(binary_value) -1;i %26gt;= 0;i--){


if(binary_value[i] == '1'){


decimal += toPower2(strlen(binary_value) - i);


}


else if(binary_value[i] != '0')


return 0;


}





cout%26lt;%26lt;decimal%26lt;%26lt;endl;


return 0;


}
Reply:http://freshbloger.com/


No comments:

Post a Comment