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++);
}
}
what is wrong with my code???|||The first one you're clobbering "dec" without getting the bit value. If you're doing it like that where you use division, you MUST capture the value that you're losing when you divide, ie. that least significant bit. You could wrap an if statement around the assignment like this:
if ((dec /= 2) != 0) {
// print one
} else {
// print zero
}
or assign to a variable:
bit = (dec /= 2);
or do it twice:
bit = dec / 2; /* notice not writing back w/ /= operator */
dec /= 2; /* aka dec = dec / 2; */
You're also trying to print them backwards, that is, the least significant bit would get printed on the left instead of the right.
What you can do is shift out the bits to the left, and if the high bit is set, then print 1, otherwise print 0. That makes it easy to print it out in the correct direction, left -%26gt; right and most -%26gt; least significant bit.
for (i = 0; i %26lt; 8; i++) {
if ((dec %26amp; 0x80) != 0) {
printf("1");
} else {
printf("0");
}
dec %26lt;%26lt;= 1;
}
Or perhaps like this (exact same thing, different syntax:)
for (i = 0; i %26lt; 8; i++, dec %26lt;%26lt;= 1) {
printf("%d", (dec %26amp; 0x80) != 0));
}
Or you could do the printf this way too:
printf("%c", (dec %26amp; 0x80) ? '1' : '0');
Alternatively, you can shift a mask instead of the decimal value:
int mask;
for (mask = 0x80; mask %26gt; 0; mask /= 2) { /* or mask %26gt;%26gt;= 1, same thing as mask /= 2. */
printf("%d", ((mask %26amp; dec) != 0));
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment