I want to convert decimal to binary but it prints it binary in reverse order without array. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I want to convert decimal to binary but it prints it binary in reverse order without array.

For example For 8 it prints 0001 But actually it is 1000 **************** #include<iostream> using namespace std; int main() { int num,i=0; cin>>num; while(num>0) { i=num%2; num=num/2; cout<<i; } system("pause");return 0; }

16th Oct 2019, 6:58 AM
M Abdur Rafey Ahmed
M Abdur Rafey Ahmed - avatar
3 Answers
16th Oct 2019, 8:15 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
0
You can change the order of the numbers by using a for loop and writing every number into an array. Something like this: arr oldByteArray[8]; //the order here is 0001 arr newByteArray[8]; for(int i = 0; i < sizeof(oldByteArray); i++) { newByteArray[i] = oldByteArray[8 - i]; }
16th Oct 2019, 7:43 AM
TheLastCookie
TheLastCookie - avatar
0
Yes it prints 0001 coz algo you put is right just print your number in reverse using any loop . This is my program. I do this like this. for(i=0; n>0; i++)     {     a[i]=n%2;     n= n/2;   }        for(i=i-1 ;i>=0 ;i--)     {     cout<<a[i];     }
16th Oct 2019, 7:44 AM
Chirag Kumar
Chirag Kumar - avatar