### binary calculator problem

i am writing a program for binary calculator. here is my code:
 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546`` ``````#include #include 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: "<>a; cout<<"enter decimal number b:"<>b; string s1= decimalToBinary(a); string s2= decimalToBinary(b); cout<<"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 ="<>3= "<

problem is program is not working correctly.
Last edited on
line 16: `unsigned int a=0,b=0;`
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
this is a matter of formatting. See the example

http://www.cplusplus.com/reference/ios/ios_base/width/

on line 39 the variable `s3` (I guess) is missing
ok i read it and here is what i tried
line 39
 ``1234`` ``````cout<<"a & b="; cout.fill(0); cout.width(8); cout<

Last edited on
hm, you need to learn the difference between `char` and `int`

line 1: `cout.fill('0'); // Note the '' `
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!!
 is there any shorter way out.
You can also use setw() and setfill() within the stream (don't forget to `#include <iomanip> `)

http://www.cplusplus.com/reference/iomanip/setfill/

it's shorter but also reset after first appearance (otherwise you would have output like 00000a=)
okay thanks a lot. here is my final code:
 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647`` ``````#include #include #include 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 int a=0,b=0; cout<<"enter decimal number a: "; cin>>a; cout<>b; string s1= decimalToBinary(a); string s2= decimalToBinary(b); cout<<"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="<>3= "<
Topic archived. No new replies allowed.