In C++ Write a program that will convert a string of binary digits to their decimal equivalent. For convenience limit the binary number to 16 bits. Write the decimal equivalent to the screen. For this program you must read in the binary number as a string type. If you were to enter a large binary number like 110110001100111 as a decimal value it would be too large to fit in an int type.
#include <iostream> #include <string> using namespace std; int main() { string s; cout << "Enter a binary number: "; cin >> s; long d = 0; for (int i = 0; i < s.size(); ++i) { d *= 2; d += s[i] - '0'; } cout << s << " in decimal is " << d << endl; return 0; }
Get Answers For Free
Most questions answered within 1 hours.