Aug 13, 2013 at 1:25pm UTC
i am writing a program for binary calculator. here is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include<iostream>
#include<string>
using namespace std;
string decimalToBinary(unsigned char num)
{
if (num==0) return "0" ;
if (num==1) return "1" ;
if (num%2==0)
return decimalToBinary(num/2)+"0" ;
else
return decimalToBinary(num/2)+"1" ;
}
int main()
{
unsigned char a=0,b=0;
cout<<"enter decimal number a: " <<endl;
cin>>a;
cout<<"enter decimal number b:" <<endl;
cin>>b;
string s1= decimalToBinary(a);
string s2= decimalToBinary(b);
cout<<"a= " <<a<<"in binary is " <<s1<<endl;
cout<<"b= " <<b<<"in binary is " <<s2<<endl;
unsigned char c = a&b;
unsigned char d=a||b;
unsigned char e= ~a;
unsigned char f=~b;
unsigned char g = a<<2;
unsigned char h= a>>3;
unsigned char i=a^b;
string s3= decimalToBinary(c);
string s4= decimalToBinary(d);
string s5= decimalToBinary(e);
string s6= decimalToBinary(f);
string s7= decimalToBinary(g);
string s8= decimalToBinary(h);
string s9= decimalToBinary(i);
cout<<"a & b =" <<endl;
cout<<"a|b= " <<s4<<endl;
cout<<"~a =" <<s5<<endl;
cout<<"~b =" <<s6<<endl;
cout<<"a^b=" <<s9<<endl;
cout<<"a<<2 =" <<s7<<endl;
cout<<"b>>3= " <<s8<<endl;
}
problem is program is not working correctly.
Last edited on Aug 13, 2013 at 1:27pm UTC
Aug 13, 2013 at 1:33pm UTC
line 16: unsigned int a=0,b=0;
Aug 13, 2013 at 1:38pm UTC
that made some improvement. I am however trying to achieve an output similar to this:
A = 5 in binary is 00000101
B = 8 in binary is 00001000
A & B = 00000000
A | B = 00001101
~A = 11111010
~B = 11110111
A ^ B = 00001101
A << 2 = 00010100
B >> 3 = 00000001
Aug 13, 2013 at 2:11pm UTC
ok i read it and here is what i tried
line 39
1 2 3 4
cout<<"a & b=" ;
cout.fill(0);
cout.width(8);
cout<<right<< s3<<endl;
even bad output
Last edited on Aug 13, 2013 at 2:12pm UTC
Aug 13, 2013 at 2:17pm UTC
hm, you need to learn the difference between char
and int
line 1: cout.fill('0' ); // Note the ''
Aug 13, 2013 at 2:23pm UTC
my bad i missed ' '. code seemed to be working now. i however have one question. i now have to set width and pad '0' for every cout operation. is there any shorter way out.
by the thanks coder777 you have always helped me a lot!!