Thursday, December 15, 2011

C++ program converting binary to decimal?

what do i need to change this module to make it work, i did not declare any variables in the main function.








void BinToDec()


{ double dec;


int len;


string bin;


bin= “ ”





cout %26lt;%26lt;"Converting from Binary to Decimal number. Please enter a binary number" %26lt;%26lt;endl;


len=bin.len()


for (i=1; i%26lt;=len ; i++)


if (bin.at(i-1)==’1’)


dec = dec + pow(2, len-i);


}|||Also, you are not initializing dec, its value will be whatever garbage was left in memory.





Also again, using a double and calling pow is a waste, binary numbers are always whole numbers (except for IEEE-spec floating point registers, but that clearly does not apply here.)





Use the left-shift operator instead, it is much more efficient:





unsigned long dec = 0;


int len = bin.len();


for (i = len - 1; i %26gt;= 0; i--)


   if (bin.at(i) == '1')


      dec |= (1 %26lt;%26lt; i);|||Well for starters, after this:





cout %26lt;%26lt;"Converting from Binary to Decimal number. Please enter a binary number" %26lt;%26lt;endl;





You are asking the user to enter a binary number, yet, you have no input requests in your function such as:





getline(std::cin, bin);

No comments:

Post a Comment