1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
/** * CONVERTING BINARY TO DECIMAL IN C++ codebind.com * */ #include <iostream> #include <iomanip> #include <string> #include <climits> using namespace std; const size_t maxBits = sizeof(short) * CHAR_BIT; int main(int argc, char *argv[]) { string line; bool inputOk; short n; while (true) { cout << "Enter binary number (" << maxBits; cout << " bits or less) : " << endl; do { cout << "> "; getline(cin,line); inputOk = true; for (size_t i = 0; (i < line.size()) && (inputOk == true); i++) { if ((line[i] != '0') && (line[i] != '1')) { inputOk = false; cout << "non-bit entered" << endl; } } if ((inputOk == true) && (line.size() > maxBits)) { inputOk = false; cout << "too big for " << maxBits << "-bit integer" << endl; } } while (inputOk == false); // Convert string of bits to an integer n = 0; for (int i = line.size()-1, j = 0; i >= 0; --i,j++) { n |= (line[i] - '0') << j; } cout << line << " = " << n << endl; } return 0; } /* OUTPUT: Enter binary number (16 bits or less) : > 101000 101000 = 40 Enter binary number (16 bits or less) : > 10 10 = 2 Enter binary number (16 bits or less) : > 10 10 = 2 Enter binary number (16 bits or less) : > 101 101 = 5 Enter binary number (16 bits or less) : > */ |
Different ways of Putting the above question
- Binary To Decimal Conversion in C++
- Convert Binary to Decimal and from Decimal to Binary
- how to convert decimal to binary
- Converting binary to decimal using recursion
- i need code for binary to decimal (it should be written in C++
- Converting Binary to Decimal using while loop in C++
- Write a c++ program to convert binary number to decimal number