### Binary to Decimal and reverse

I see these two question in my book, the first one I make it out, but the second one puzzles me, how ?
12.8.5 Binary to Decimal
Write a program that asks the user to input a binary string (e.g., “11100010101”). Note that the input is a string, not a number. The string specifies a binary number. The program then is to convert the binary number which the string specifies into a decimal number and output the result. Your output should look like this:
 ```Enter a binary string: 101 101 = 5 in decimal. Press any key to continue. ```

12.8.6 Decimal to Binary
Write the reverse conversion of Exercise 12.8.5. That is, write a program that asks the user to input a decimal number (this time it is not a string but a number). The program then is to convert the decimal number which the user entered into a binary string(e.g., “11100010101”) and output the result. Your
output should look like this:
 ```Enter a decimal number: 14 14 = 1110 in binary. Press any key to continue. ```
here's my Binary to Decimal:
 ``12345678910111213141516171819202122232425`` ``````int BinToDec(string s); int main() { string s; cout << "enter string by binary: " << endl; getline(cin, s); int result = BinToDec(s); cout << "decimal: " << result << endl; system("pause"); return 0; } int BinToDec(string s) { int len = s.length(); int result = 0; for(int i = 0; i < len; i++) { int pow = 0; if(s[i] == '1') { pow = 1; for(int j = 0; j < (len - i -1) ; j++) pow *= 2; } result += pow; } return result; }``````
I also want to know that the binary output must be a string ?
if not, can you guys give me some examples to do the conversion?
Does your decimal have to be a string, too? Edit: reread the orig. post...
Last edited on
1.

 ``12345`` ``````std::string binary_string b( "11100010101" ); std::cout << std::accumulate( binary_string.begin(), binary_string.end(), 0u, []( unsigned int s, char c ) { return ( 2 * s + ( c -'0' ) ); } ) << std::cout; ``````

2.

 ``1234567`` ``````[code]unsigned int x = UINT_MAX; std::string binary_string; do { binary_string.push_back( x % 2 + '0' ); } while ( x /= 2 ); std::reverse( binary_string.begin(), binary_string.end() ); std::cout << UINT_MAX << " = " << binary_string << std::endl;``````
Last edited on
Topic archived. No new replies allowed.