Thursday, December 15, 2011

Converting decimal to binary using a for loop?

I can't seem to think what is wrong with my loop. (Note: This is C code). It's basically suppose to print out 8 bits. The user basically enters in a intager %26amp; the program converts that int to a binary number 8 bits long. Can someone help?





I'm learning C right now %26amp; I have to covert decimal to binary. And I'm having issues printing 8 bits of binary. I know how to convert decimal to binary by hand, but I don't understand what I am doing wrong in my program. How can I print 8 bits of binary in a for loop?





MY CODE:


===============================


#include %26lt;stdio.h%26gt;





void main()


{


//declare %26amp; initialize variables


int dec = 0; //decimal number


int dect = 0; //test the decimal


int i; //counter


int bitAmount = 3; //amount of bits to shift





//prompt user to enter int


printf("Enter a integer: ");


scanf("%d", %26amp;dec);





//convert the decimal into binary


for (i = 0; i %26lt; 8; i++) //print out 8 bits


{


//divide so you only get 0 or 1


if (dec != 0)


{


dec = dec % 2;





//extract the number


dec = dec / 2;


}


else


dec = 1;





//print the binary


printf("%d ", dec);





}





//pause screen


system("pause");


}





void dec2bin(int dec, char direction, int bitAmount)


{


int i; //counter





//convert the decimal to a binary


for (i = 0; i%26lt;=10, dec !=0; i*=10)


{


//divide to get only 0 %26amp; 1


dec = dec % 2;





//extract each number


dec = dec / 2;





//print each bit


printf("%d ", dec++);


}








}|||Here is your problem


dec = dec % 2;





The first time into the loop dec, the number to be converted suddenly becomes 0 or 1. You have now lost your number!


The sum should be


rem = dec % 2;





The first time through the loop rem will be the right hand digit.


The second time through the loop you need to add the new rem to the previous rem in such a way as to get a left hand digit and the previous right hand digit. I think there needs to be a multiply by 10 or a multiple of 10 depending on the digit position.





So the sum should really be something like


rem = rem + ((dec % 2) * pow(10,i));





Needs math.h





Have fun.|||What's happening is that essentially in one iteration of the loop, dec is being set to 0 (any number modulus 2 divided by 2 = 0) and then the next iteration it is being set to 1, and then 0 again, etc.





You can do some different things. The most obvious to a C programmer would be to use bitwise functions and just do dec %26gt;%26gt; i %26amp; 1 which would shift it right i bits and then remove all but the first bit, which should give you each bit.





For example, this works: http://paste2.org/p/1020986 Also, note the backwards loop; this is needed because we want to print the last character to the output first because binary is written highest bit on the right to lowest bit (1) on the left.

No comments:

Post a Comment