Thursday, December 15, 2011

Convert base10 to binary numbers w/ c++?

I've spent all day trying to figure out how to do this. We can't use shortcuts/built in functions. We need 8 if then statements. I'm assuming that's for 128, 64, 32, 16, 8, 4, 2, 1 right? (we're only required to go up to 8 numbers) I thought I made the correct program but it never works. can someone maybe show me a line or two of what to do? Thanks so much!





#include %26lt;iostream%26gt;





using std::cout;


using std::cin;


using std::endl;





int main ()


{


//declare variables


int n1 = 0;


int n2 = 0;


int n3 = 0;


int n4 = 0;


int n5 = 0;


int n6 = 0;


int n7 = 0;


int n8 = 0;








//enter input items


cout %26lt;%26lt; "Please enter a number between 0 and 255: " ;


cin %26gt;%26gt; n1;











//conversion


//128


if (n1 %26gt;= 128)


{


n1 = 1;


}


else


{


n1 = 0;


}


cout %26lt;%26lt; "Binary: " %26lt;%26lt; n1;





//64


n2 = n1 - 128;





//64


n2 = n1 - 128;





if (n2 %26gt;= 64)


{


n2 = 1;


}


else


{


n2 = 0;


}


cout %26lt;%26lt; n2;





//32


n3 = n2 - 64;





if (n3 %26gt;= 32)


{


n3 = 1;


}


else


{








ETC...|||//conversion


//128


if (n1 %26gt;= 128)


{


na = 1;


n1 = n1 - 128;


}


else


{


na = 0;


}


cout %26lt;%26lt; "Binary: " %26lt;%26lt; na;





//64





Do the subtraction only if the number is large enough!|||you are over writing the initial data when you set n1=1;


This causes you to have n2=-127





the best way to get around this is to put the initial data into a separate variable n then do the following;





if (n%26gt;= 128)


{ n1=1; n=n-128;}





if (n%26gt;=64)


{n2=1; n=n-64;}





ETC...





Putting the subtractions in the if statement ensues that you do not subtract the value unnecessarily.





since you have already initialized the values to zero the else statements are unnecessary.





There is another way to solve this problem using loops and division and mod functions. It is mathematically more difficult.





if you were going to have to solve for a larger number I would try it out.





But this should solve you problem, and that would require me to think for a while as i have not used it in several years.

No comments:

Post a Comment