just a question?

hey guys ive been doing this for an hour now this is a decimal to binary converter that ive been working on and i got the answer but i have to use an array to be able to do so . do any of you know how to do this without an array , if you do please let me look at your code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
	int x,xc, rem;
	int binary[7];/* i used array because i dont know how to reverse the 
                         binary digits so the only solution i could think of is array*/
	int y=0;
	cout<<"Enter a decimal number : ";
	cin>>x;
	xc=x;
	for(;x!=0;)
	{
		rem=x%2;
		binary[y]=rem;
		x=x/2; 
		y++;	
}
	y--;
	cout<<endl;
	cout<<"The binary representation of "<<xc<<" is ";
	for(y; y>=0; y--)
	cout<<binary[y];
Last edited on
You could start with a really big power of 2. Something like 2^15. Then see if the number that is in decimal is bigger or smaller than the current power of 2. If it is bigger, the next bit is a 1 and you subtract the current power of 2 from the number. If it is smaller, the next bit is a 0. Regardless of smaller or bigger, you reduce the current power of 2 by half. And repeat until the number is 0.
This approach makes the following assumption. Starting at 2^15 assumes that the number needs at most 15 bits to represent the number's binary form.
You might also want to think about how many bits a c++ integer can hold. On my system int can hold 16 bits, long can hold 32 bits, and long long can hold 64 bits. Just do not forget that all three of those types are signed integers. Meaning that the very first bit is reserved for holding the sing of the integer (positive or negative). Which means that the largest positive int type variable can be only 2^15 on my system. There are also unsigned types that you can learn about if you want to use that first bit.
Last edited on
Topic archived. No new replies allowed.