Create a class named as Bitkaar. Take a number 65535. Create functions to print in binary, decimal and hexadecimal. Print number in binary by using the algorithm discussed in the class. For Decimal and Hexadecimal build a logic by your own thinking.
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
class Bitkaar{
private:
int number;
string hexStr;
long long binaryNumber;
public:
//Constructor
Bitkaar(int number){
this->number=number;
this->hexStr="";
this->binaryNumber=0;
}
//print in binary, decimal and hexadecimal
void printInBinary(){
int digits[10000];
int counter=0;
int numberToBinary=this->number;
for(counter=0; numberToBinary>0; counter++){
digits[counter]=numberToBinary%2;
numberToBinary/=2;
}
int numbers[10000];
int i=0;
int size=counter;
cout<<"Number in binary: ";
for(counter=counter-1 ;counter>=0 ;counter--){
cout<<digits[counter];
numbers[i]=digits[counter];
i++;
}
for (int i = 0; i < size; i++) {
this->binaryNumber *= 10;
this->binaryNumber += numbers[i];
}
cout<<"\n";
}
//binary to decimal
int binaryToDecimal(long long n)
{
int decNumber = 0;
int i = 0;
int rem;
while (n!=0){
rem = n%10;
n /= 10;
decNumber += rem*pow(2.0,i);
++i;
}
return decNumber;
}
//hexadecimal to decimal
int hexadecimalToDecimal(string hexStr){
int decimalNum=0;
int rem;
int i=0;
int length=0;
length=hexStr.length()-1;
i=hexStr.length();
i=0;
while(length>=0)
{
rem = hexStr[length];
if(rem>=48 && rem<=57)
rem = rem-48;
else if(rem>=65 && rem<=70)
rem = rem-55;
else if(rem>=97 && rem<=102)
rem = rem-87;
decimalNum = decimalNum + (rem*pow(16.0, i));
length--;
i++;
}
return decimalNum;
}
//print in Decimal
void printInDecimal(){
//binary to decimal
cout<<"Binary to decimal: "<<binaryToDecimal(this->binaryNumber)<<"\n";
cout<<"Hexadecimal to decimal: "<<hexadecimalToDecimal(hexStr)<<"\n";
}
//print in Hexadecimal
void printInHexadecimal(){
char hex[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int numberToHex=this->number;
while(numberToHex>0)
{
int r = numberToHex % 16;
hexStr = hex[r] + hexStr;
numberToHex/=16;
}
cout<<"Number in hexadecimal: "<<hexStr<<"\n";
}
};
//The start point of the program
int main (){
int number=-1;
while(number<0){
cout<<"Enter integer number: ";
cin>>number;
}
Bitkaar bitkaar(number);
bitkaar.printInBinary();
bitkaar.printInHexadecimal();
bitkaar.printInDecimal();
system("pause");
return 0;
}
Comments
Leave a comment