Advertisement
Ivan_Bochev

BinaryToDecimal&&<-C++

Feb 26th, 2021
1,534
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <string>
  4. using namespace std;
  5.  
  6. string decToBin(int dec) {
  7.     int i;
  8.     string txt="";
  9.     string bin="";
  10.     while(dec!=0){
  11.         if(dec%2==0){
  12.             txt+="0";
  13.         } else{
  14.             txt+="1";
  15.         }
  16.         dec/=2;
  17.     }
  18.     for(i = txt.size()-1; i >= 0; i--){
  19.         bin+=txt.at(i);
  20.     }
  21.     return bin;
  22. }
  23.  
  24. int binToDec(int bin) {
  25.     int dec = 0;
  26.     int power = 0;
  27.     while (bin != 0) {
  28.         dec += (bin % 10) * pow(2, power);
  29.         power++;
  30.         bin /= 10;
  31.     }
  32.     return dec;
  33. }
  34.  
  35. int main() {
  36.     while (true) {
  37.         cout<< endl<< "1: BIN -> DEC";
  38.         cout<< endl<< "2: DEC -> BIN";
  39.         cout<< endl<< "3: EXIT"<< endl;
  40.         cout<< endl<< "What is your choice: ";
  41.         int choice;
  42.         cin>> choice;
  43.         switch (choice) {
  44.         case 1:
  45.             cout<< endl<< "Enter binary number: ";
  46.             int bin;
  47.             cin>> bin;
  48.             cout<< endl<< "Decimal number: "<< binToDec(bin)<< endl;
  49.             break;
  50.         case 2:
  51.             cout<< endl<< "Enter decimal number: ";
  52.             int dec;
  53.             cin>> dec;
  54.             cout<< endl<< "Binary number:"<< decToBin(dec)<< endl;
  55.             break;
  56.         case 3:
  57.             break;
  58.         default:
  59.             cout<< endl<< "Wrong choice! Try again!" << endl;
  60.         }
  61.         if (choice == 3) {
  62.             break;
  63.         }
  64.     }
  65.     return 0;
  66. }
  67.  
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement