DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Code Snippet: binary to decimal convertor (http://www.daniweb.com/forums/thread217383.html)

tux4life May 24th, 2009 1:16 pm
binary to decimal convertor
 
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. ...

  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. }
amrith92 May 24th, 2009 3:24 pm
Nice code! But maybe the function name
pow
should be changed, to avoid any ambiguity caused if anybody chooses to include
<cmath>
with that :) ...

tux4life May 24th, 2009 4:48 pm
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 :P

William Hemsworth May 25th, 2009 12:00 pm
Here's how I would have done it:
#include <iostream>
using namespace std;

int main() {
  char binary[33]; // 32bit + '\0'
  unsigned int decimal = 0;

  cout << "Enter binary:\n> ";

  cin.getline( binary, 32 );
  unsigned int exp = 1;

  for (int i = (int)strlen( binary ) - 1; i >= 0; --i) {
    if ( binary[i] == '1' )
      decimal += exp;

    exp <<= 1;
  }

  cout << "\nDecimal:\n> " << decimal;

  cin.ignore();
}

tux4life May 25th, 2009 12:48 pm
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 :) !!


All times are GMT -4. The time now is 12:06 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC