Need Help in converting decimal to binary and vice versa using class.What is wrong in this code?

#include<iostream>

using namespace std;

class Numberconversion{
int x,y;
public:
void set_bin(int m);
int get_bin();
void set_dec(int n);
int get_dec();
};

void Numberconversion::set_bin(int m){
m=x;
int a,i,sum=0;
while(m!=0){
a=m%2;
m=m/2;
sum=(a*i)+sum;
i=i*10;
}

}
int Numberconversion::get_bin(){
return x;
}

void Numberconversion::set_dec(int n){
n=y;
int b,j,s=0;
while(n!=0){
b=n%10;
n=n/10;
s=(b*j)+s;
j=j*2;

}


}

int Numberconversion::get_dec(){
return y;
}

int main(){
Numberconversion n;
n.set_bin(14);
n.set_dec(1101);

cout<<"binary:"<< n.get_bin()<<endl;
cout<<"decimal:"<<n.get_dec()<<endl;

return 0;

}
I don't think using a class here really makes sense, but if you have too okay. Let's break down number bases with an example. If you wanted to convert 14 to binary, I would first find out how many digits you need. All you need to do this is find out two to the power of what is greater than 14:
1
2
3
4
5
2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16

Alright, 2^4 is the first power of two larger than 14, so we know we'll need 4 bits to represent 14 in binary. Now we start from right to left, setting bits to one if they fit:. We know that 2^4 is too large, so we'll start with 2^3.
1
2
3
4
2^3 = 8  We can fit 8 into 16, so make that bit a 1.  Now we only need to represent 8.  Our binary number is now 1000.
2^2 = 4  We can fit 4 into 8, so make that bit a 1 as well.  Our number is now 1100, and we only need to represent 2 now.
2^1 = 2   We can fit 2 into 2, so make that bit a 1 as well.  Our number is now 1110, and we only need to represent 0 now.
2^0 = 1  We can't fit 1 into 0, so make that bit a 0.  Our number stays as 1110. 

That's pretty much it :)
Last edited on
Topic archived. No new replies allowed.