Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //pastebin.com/u/thewhitefang
- //Midterm Q1
- #include <iostream>
- #include <string>
- #include <fstream>
- using namespace std;
- // Incomplete Class
- class DecBin{
- private:
- int m_Decimal;
- string m_Binary;
- public:
- DecBin(int inDec){
- if (inDec < 255){
- m_Decimal = inDec;
- DecToBin(inDec);
- }
- else
- {
- m_Decimal = 0;
- }
- }
- void LeftShiftBin(int inBin){
- string temp;
- temp.assign(m_Binary);
- temp = m_Binary.substr(0, inBin); //temp will store the shifted bits
- m_Binary.append(temp); //append temp to the back
- m_Binary.erase(0,inBin);
- /*m_Binary = x;*/
- BinToDec(m_Binary);
- }
- void DecToBin(int inDec){
- //iterative - will repeat until inDec < 0
- while (inDec > 0)
- {
- //if got remainder, add 1 infront
- if (inDec % 2 != 0)
- {
- m_Binary = '1' + m_Binary;
- }
- else
- {
- m_Binary = '0' + m_Binary;
- }
- inDec = inDec / 2;
- }
- while (m_Binary.length() != 8)
- {
- m_Binary = '0' + m_Binary;
- }
- }
- int GetDecimal(){
- return m_Decimal;
- }
- void GetBinary(string &inBin){
- inBin = m_Binary;
- }
- void BinToDec(string inBin){
- /*std::string::size_type sz;*/
- /*int temp;
- temp = stoi(inBin,nullptr,2);*/
- reverse(inBin.begin(), inBin.end());
- m_Decimal = 0;
- for (int i = 0; i < inBin.size(); ++i) {
- m_Decimal += (int(inBin[i])-48)*pow(2, i);
- // 48 is '0' converted from string
- }
- }
- };
- //string CConversion::decimalToBinaryRecursive(int num)
- //{
- // if (num <= 0)
- // {return "";}
- // else
- // {
- // if (num % 2 != 0)
- // {
- // return decimalToBinaryRecursive(num / 2) + '1';
- // }
- // else
- // {
- // return decimalToBinaryRecursive(num / 2) + '0';
- // }
- // }
- //
- //}
- int main(){
- int decimal;
- cout << "Enter a decimal number between 0 & 255: ";
- cin >> decimal;
- DecBin obj(decimal);
- string bin;
- string z = { "0" };
- /*int x;
- x = (int(z[0]));
- cout << x << endl << endl;*/
- obj.GetBinary(bin);
- cout << "Before left shift. Binary of decimal " << decimal << " is: " << bin << endl;
- obj.LeftShiftBin(2);
- obj.GetBinary(bin);
- cout << "After left shift. Decimal of binary " << bin << " is: " << obj.GetDecimal() << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement