binary to decimal convertor

Please support our C++ advertiser: Intel Parallel Studio Home
tux4life tux4life is offline Offline May 24th, 2009, 1:16 pm |
0
This snippet allows you to convert a text representation(*) of a binary number to a decimal number

(*): With 'text representation' I mean for example a string containing "1001" or "10001110011", etc. ...
Quick reply to this message  
C++ Syntax
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. unsigned int pow(unsigned int a, unsigned int n);
  7.  
  8. int main()
  9. {
  10. string binary;
  11. unsigned int decimal = 0;
  12.  
  13. cout << "Enter a binary number: ";
  14. cin >> binary;
  15.  
  16. for(int i = binary.length()-1; i >= 0; i--) {
  17. if(binary[i] > '1' || binary[i] < '0') {
  18. cout << "Invalid binary number!" << endl;
  19. return 1;
  20. } else {
  21. decimal += (binary[i] - '0') * pow(2, (binary.length()-i-1));
  22. }
  23. }
  24.  
  25. cout << "Decimal: " << decimal << endl;
  26. return 0;
  27. }
  28.  
  29. unsigned int pow(unsigned int a, unsigned int n)
  30. {
  31. unsigned int r = 1;
  32. while( n-- > 0 ) r *= a;
  33. return r;
  34. }
0
amrith92 amrith92 is offline Offline | May 24th, 2009
Nice code! But maybe the function name pow should be changed, to avoid any ambiguity caused if anybody chooses to include <cmath> with that ...
 
0
tux4life tux4life is offline Offline | May 24th, 2009
Yep, there you've got a point!
For those who are using the cmath library:
Change the name of the pow function to apow/mypow/pow2 or whatever you like
 
0
William Hemsworth William Hemsworth is offline Offline | May 25th, 2009
Here's how I would have done it:
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5. char binary[33]; // 32bit + '\0'
  6. unsigned int decimal = 0;
  7.  
  8. cout << "Enter binary:\n> ";
  9.  
  10. cin.getline( binary, 32 );
  11. unsigned int exp = 1;
  12.  
  13. for (int i = (int)strlen( binary ) - 1; i >= 0; --i) {
  14. if ( binary[i] == '1' )
  15. decimal += exp;
  16.  
  17. exp <<= 1;
  18. }
  19.  
  20. cout << "\nDecimal:\n> " << decimal;
  21.  
  22. cin.ignore();
  23. }
 
0
tux4life tux4life is offline Offline | May 25th, 2009
I'm glad to know that there was actually no need for a separate function like pow, the bit shifting is a superior method to multiplicate it every time by two!
And William, your program will threat any other value than '1' as a '0', this isn't wrong IMO, but I only wanted to let you know in case you didn't (but probably you did know this already, because you're always one step ahead )
I learned again from your code, you're superior in writing efficient and very easy to understand code !!
 
 

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC