-
Need comment
I am a beginner of C, I having the following example, but I don't understand the line
1) "int MASK = 1<<(count-1);" and
2) "while(count--)
{
printf("%d", ( byte & MASK ) ? 1 : 0 );
byte <<= 1;
}"
Can you please expain to me. Thanks a lot.
************************************************** **
#include <stdio.h>
void binary_op( int byte );
main()
{
int byte=55;
binary_op( byte );
}
void binary_op( int byte )
{
int count=8;
int MASK = 1<<(count-1);
while(count--)
{
printf("%d", ( byte & MASK ) ? 1 : 0 );
byte <<= 1;
}
printf("\n");
}
-
Well, if you are a beginner, these lines are code could be difficult. I'll touch upon them.
> 1) "int MASK = 1<<(count-1);" and
2) "while(count--)
Okay, line #1 is doing a bitshift to assign the value to MASK. And line 2 is testing to see if count is not 0 yet. If it is, then the while loop does not continue. Understand?
--Garfield
-
This is a way to print out a byte in binary. Since an int is more than one byte (usually two bytes or four bytes), the function can be easily changed to print out the whole int (change count=8 to count = 8*sizeof(int). If you know hexadecimal, it's easier to see by changing byte to various values like this:
int byte=0xff;
//int byte=0x80;
//int byte=0x77;
Code:
void binary_op( int byte )
{
int count=8;
int MASK = 1<<(count-1); //shift a one into the 8th bit position
while(count--) //loop 8 times
{
printf("%d", ( byte & MASK ) ? 1 : 0 );
//If there is a 1 at the bit position where mask has a 1, print a 1, else print a 0.
//So this prints starting with the most significant bit.
byte <<= 1; //Check the next bit
}
printf("\n");
}
-
for(x=0;x<8;x++)printf("%d",((byte&(1<<x))?1:0) );
Quzah.
-
> for(x=0;x<8;x++)printf("%d",((byte&(1<<x))?1:0) );
Wow ::staring in awe:: that's pretty good to change all of that into...this. Niiiiice.
--Garfield
-
for(x=0;x<8;x++)printf("%d",((byte&(1<<x))?1:0) );
doesn't that print the bits the wrong way round??
-
For a single byte it doesn't matter. It only matters what way you decide to view it. Multi byte variables (int / long) have an "endian" which is different on compilers.
It doesn't matter what way you display a single byte so long as you know how it's working. My display is "least significant bit first".
You could just as easily do:
for(x=7;x>-1;x--)printf("%d",((byte&(1<<x))?1:0) );
Most significant bit first.
Quzah.