help with basic decimal to binary converter

oke here is the problem.
i have made a simple decimal to binary converter but the binary is standing in reverse order, how can i do it correct?

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
#include <iostream>

using namespace std;

int main()
{
	unsigned short a, b, n;
	bool check;
	check=false;

	cout << "input: ";
	cin >> n;
	cin.ignore();
	cout << "\nbinary value: ";
	
	while(check==false)			//Loop
	{
	b=n%2;						//The algorythem
	n/=2;						
	cout << b;
	if(n==0)check=true;			//As long as the number is higher than 0
	}
	cin.get();
	return 0;
}
Hi,

the algorithm you use for the conversion just gets the most significant bit first. save them in a c++ string;

otherwise, you could do some low level magic with bitwise operators to reverse your number first, and then output it. Im not going to write that for you, but see this site and google is your friend:
http://graphics.stanford.edu/%7Eseander/bithacks.html#BitReverseObvious

There is also a book called hackers delight, which is great if you want to wet your appetite on bitwise operations...

this is what i would come up with:

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

#include <string>
#include <iostream>

using namespace std;

int main()
{
	ushort num;
	string bits;

	bits.reserve( sizeof( ushort ) * 8 ); 	// make sure it only allocates the needed memory
	
	cout << "input: ";
	cin  >> num;
	  
	cin.ignore();
	cout << "\nbinary value: ";
		
		
	do
	{
		bits.insert( 0, num & 1? "1" : "0" ); 	// if unsure about this syntax, check "ternary operator"
		num >>= 1;				// this is a shift, it does the same as an optimised division by 2.
	}						// probably your compiler would generate this anyway
	while( num );

		
	cout << bits << std::endl;

	return 0;
}



One strange thing is that input of -1 gives a value of 2052. This is trough some peculiarity of how cin interpretes "-1" to ushort... I don't have a clue where the value 2052 comes from though.
Last edited on
Topic archived. No new replies allowed.