how to write a program to convert decimal to binary, and binary to decimal as user input? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

how to write a program to convert decimal to binary, and binary to decimal as user input?

21st Jan 2017, 7:03 PM
Edrees Noori
Edrees Noori - avatar
6 Answers
+ 1
My attempt is on my profile, but also here: #include <iostream> using namespace std; int DecToBin(int num){ if (num%64==0){ cout << "1"; num -=64; if(num %32 == 0){ cout << "1"; num -=32; if(num%16==0){ cout << "1"; num-=16; if (num%8 == 0){ cout << "1"; num-=8; if (num%4==0){ cout << "1"; num-=4; if (num%2==0){ cout << "1"; num-=2; if(num%1==0){ cout << "1"; num-=1; }else{cout << "0";} }else{cout << "0";} }else{cout << "0";} }else{cout << "0";} }else{cout << "0";} }else{cout << "0";} }else{cout << "0";} } int main() { int DecToInt(32); } // Currently gives no output
21st Jan 2017, 7:21 PM
Aaron
Aaron - avatar
0
I did one about base changing, go and see :) @Aaron you called DecToInt but your function is named DecToBin, and you can create a loop instead of all your if/else :)
21st Jan 2017, 7:32 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
Baptiste, can you link it? I knew there was something blaringly obvious wrong, thanks
21st Jan 2017, 7:34 PM
Aaron
Aaron - avatar
0
@Aaron yes of course : https://code.sololearn.com/ca67km3pfxBI/#cpp No prob, those kind of problems are the trickiest ^^
21st Jan 2017, 7:37 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
#include <iostream> using namespace std; int main() { int num,arr[64]; cin>>num; int i=0,r; while(num!=0) { r = num%2; arr[i++] = r; num /= 2; } for(int j=i-1;j>=0;j--) cout<<arr[j]; return 0; } i found this online and it works...this is just decimal to binary
21st Jan 2017, 7:40 PM
Leonida17st
Leonida17st - avatar
- 1
I have no idea what the finished product would look like, but I imagine it would involve if/elif loops about num %64 and num%32 etc, I'll give it a whirl now actually
21st Jan 2017, 7:06 PM
Aaron
Aaron - avatar