c++ - Binary to Decimal and Vice Versa -


everyone! trying make small program takes in "binary"(base 2) number , convert "decimal"(base 10) number , vice versa. i'm trying stick basic operators , away advanced arrays.

here code far:

int main() {         string strput;         int numout = 0;         cout << "enter number in binary \n";         cin >> strput;         int pwr = strput.length()-1;           for(int x = 0; x <  strput.length(); x++)         {                 numout = strput[x] * pow(2,pwr);                 pwr--;                 numout += numout;         }         cout << numout < "\n";  return 0; } 

i trying take in number such "1101" , output "13". plan read in binary number , use binary multiples of 2 per each index create correct number. far more lost on doing wrong, continuously output of "98".

            numout = strput[x] * pow(2,pwr); 

lots of mistakes here:

  1. you lose old value of numout here. oops.

  2. since strput[x] contains character representations of numbers, not numbers, not have number 0 or 1 character '0' or '1'. has wrong value.

  3. don't use pow integers must exact. use binary operations.

so instead of:

    for(int x = 0; x <  strput.length(); x++)     {             numout = strput[x] * pow(2,pwr);             pwr--;             numout += numout;     } 

use:

    for(int x = 0; x <  strput.length(); x++)     {             numout += (strput[x] - '0') * (1 << pwr);             pwr--;     } 

Comments