Binary conversion

Nov 27, 2015 at 11:02pm
I am trying to figure out how to convert a number to binary. I am running into the problem where it either goes into an infinite loop or it only does one conversion. Any help just trying to figure out how to properly do the loop would be amazing, thanks.


#include <conio.h>
#include <stdio.h>
#include <Windows.h>

int main()
{
int a, b, c, d, e;


printf("Input number to convert to binary here:");
scanf("%i", &a);
flushall();
Sleep(1000);
system("cls");


c = a % 2;
printf("%i", c);

do
{

a = a / 2;

b = a % 2;
printf("%i", b);




} while (a =! 1);



getch();
return 0;
}
Last edited on Nov 27, 2015 at 11:29pm
Nov 27, 2015 at 11:46pm
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 #include <iostream>

using namespace std;

int main()
{
   int a = 0;

   cout << "Input number to convert to binary here: ";
   cin >> a;

   do
   {
      cout << a % 2;
      a = a/2;
   } while (a != 0);

return 0;
}

( reverse order )
Last edited on Nov 27, 2015 at 11:49pm
Nov 28, 2015 at 1:27am
closed account (48T7M4Gy)
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
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
	int store[100] = { 0 };
	int index = 0;

	int a = 0;

	cout << "Input number to convert to binary here: ";
	cin >> a;

	do
	{
		store[index] = a % 2;
		cout << store[index];
		a = a / 2;
		index++;
	} while (a != 0);
	cout << endl;

	for (int i = 0; i < index; i++)
		cout << store[index - i - 1];
	cout << endl;

	return 0;
}


In correct order :)
Last edited on Nov 30, 2015 at 2:35am
Nov 29, 2015 at 3:07am
WookieWarrior2 please use code tags when you are typing the code into the text box to make it easier for everyone to read your code

Example:

int main(){

return 0;

}

vs

1
2
3
4
5
int main(){

     return 0;

}


*This code is not correct and won't do anything it is just an example.
Last edited on Nov 29, 2015 at 3:09am
Nov 29, 2015 at 5:34am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// invariant: result is within ULLONG_MAX
unsigned long long to_binary( unsigned int number )
{
    if( number < 2 ) return number ;
    else return to_binary( number/2 ) * 10 + number % 2 ;
}

void print_binary( unsigned long long number )
{
    if( number < 2 ) printf( "%llu", number ) ;
    else
    {
        print_binary( number/2 ) ;
        print_binary( number%2 ) ;
    }
}

http://coliru.stacked-crooked.com/a/0a1c8ca2faa51f38
Topic archived. No new replies allowed.