C++ program to convert binary to decimal number using class

Given a binary number, we have to convert it into decimal using the class and object approach.
Submitted by Shubh Pachori, on September 09, 2022

Example:

Input:
Enter Binary digit : 10101

Output:
Decimal is 21

C++ code to convert binary to decimal number using the class and object approach

#include <iostream>
using namespace std;

// creating a class
class BinaryToDecimal {
  // private data members
 private:
  int binary;

  // public member functions
 public:
  // getBinary() function to 
  // insert binary digit
  void getBinary() {
    cout << "Enter Binary digit : ";
    cin >> binary;
  }

  // btod() function to convert binary to decimal
  void btod() {
    // initialize three int type variable 
    // for operating
    int decimal = 0, digit, base = 1;

    // a while loop to convert binary to decimal
    while (binary) {
      // reaminder of binary by 10 stored in digit
      digit = binary % 10;

      // updating binary by dividing 10
      binary = binary / 10;

      // add multiple of digit and base in decimal
      decimal += digit * base;

      // multiply it by 2
      base = base * 2;
    }
    cout << "Decimal is " << decimal << endl;
  }
};

int main() {
  // create an object
  BinaryToDecimal B;

  // calling getBinary() function to 
  // insert binary digit
  B.getBinary();

  // calling btod() function to 
  // convert Binary To Decimal
  B.btod();

  return 0;
}

Output:

RUN 1:
Enter Binary digit : 11111111
Decimal is 255

RUN 2:
Enter Binary digit : 1100110011
Decimal is 819

Explanation:

In the above code, we have created a class BinaryToDecimal, one int type array data member binary to store the binary digit, and public member functions getBinary() and btod() to store and convert the given binary to decimal number.

In the main() function, we are creating an object B of class BinaryToDecimal,  reading the binary given by the user using getBinary() function, and finally calling the btod() member function to convert the given binary. The btod() function contains the logic to convert the given binary number to decimal number and printing the result.

C++ Class and Object Programs (Set 2) »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.