![]() |
| ||
| 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. ... |
#include <iostream> #include <string> using namespace std; unsigned int pow(unsigned int a, unsigned int n); int main() { string binary; unsigned int decimal = 0; cout << "Enter a binary number: "; cin >> binary; for(int i = binary.length()-1; i >= 0; i--) { if(binary[i] > '1' || binary[i] < '0') { cout << "Invalid binary number!" << endl; return 1; } else { decimal += (binary[i] - '0') * pow(2, (binary.length()-i-1)); } } cout << "Decimal: " << decimal << endl; return 0; } unsigned int pow(unsigned int a, unsigned int n) { unsigned int r = 1; while( n-- > 0 ) r *= a; return r; }
| ||
| Nice code! But maybe the function name powshould be changed, to avoid any ambiguity caused if anybody chooses to include <cmath>with that :) ... |
| ||
| Yep, there you've got a point! For those who are using the cmathlibrary: Change the name of the powfunction to apow/mypow/pow2 or whatever you like :P |
| ||
| Here's how I would have done it: #include <iostream> |
| ||
| 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