DEV Community

Analyze_
Analyze_

Posted on • Updated on

Cpp Decimal to Binary Converter

Link

I would like to know how to add more digits, can anyone help?

#include <iostream>

int main() {
  int num = 0;
  int digit1 = 0;//128
  int digit2 = 0;//64
  int digit3 = 0;//32
  int digit4 = 0;//16
  int digit5 = 0;//8
  int digit6 = 0;//4
  int digit7 = 0;//2
  int digit8 = 0;//1
  std::string session = "y";
  while (session == "y"){

digit1 = 0;
digit2 = 0;
digit3 = 0;
digit4 = 0;
digit5 = 0;
digit6 = 0;
digit7 = 0;
digit8 = 0;
std::string cont = "";


  std::cout << "\nEnter an integer 255 or under (this binary only supports 8 digits): "; std::cin >> num; std::cout << "\n"; 
    if (num < 256) {
 if(num>127){ digit1++; num = num - 128;}
 if(num>63){ digit2++; num = num - 64;}
 if(num>31){ digit3++; num = num - 32;}
 if(num>15){ digit4++; num = num - 16;}
 if(num>7){ digit5++; num = num - 8;}
 if(num>3){ digit6++; num = num - 4;}
 if(num>1){ digit7++; num = num - 2;}
 if(num>0){ digit8++; num = num - 1;}
 std::cout << digit1 << digit2 << digit3 << digit4 << digit5 << digit6 << digit7 << digit8;
session = "y";
  std::cout << "\nContinue session? [y/n]\n";
    std::cin >> session;
      }
    else if (num > 255){
      std::cout << "You have to enter a number under 256\n[ENTER ANY KEY TO RESET]\n";
      std::cin >> cont;
      session = "y";
    }
    else{
      std::cout << "You have to enter a number above -1\n[ENTER ANY KEY TO RESET]\n";
      std::cin >> cont;
      session = "y";
    }
    std::cout << "\x1B[2J\x1B[H";//reset screen
    }//end of session
  return 1;
}
Enter fullscreen mode Exit fullscreen mode


Changelog#1(Wed, June 1st, 2022):
Added a feature so if you enter a number over 255, or under 0, it gives a message and resets
Changlelog#2(Thur, June 2nd, 2022):
Implemented console erase after calculated

Top comments (0)