Reputation: 91
I got this code here to print the binary of a decimal, if I ran this function with argument as 3, it would print 0000 0011, which is right, I understand that >> will shift the binary to the right 7 to 0 to display the binary, but I do not understand the purpose of the code: & 1 and + 0, can someone tell me what are those for?
void gal_print(gal8 a)
{
int i = 8;
while (i--)
// printf("%d", i);
putchar((a >> i & 1) + '0');
}
Upvotes: 2
Views: 101
Reputation: 67713
It actually does not have to ... (no &
, no + '0'
)
void gal_print(unsigned char a)
{
int i = CHAR_BIT;
while (i--)
{
if(((unsigned char)(((a >> i) << (CHAR_BIT - 1))) >> (CHAR_BIT - 1)))
{
putchar('1');
}
else
{
putchar('0');
}
}
}
Upvotes: 0
Reputation: 311048
This expression with the bitwise operator &
(bitwise AND operator)
a >> i & 1
is used to extract the right most bit of the number. So the result value of the expression will be either 0
or 1
.
For example
00000011 // 3
&
00000001 // 1
========
00000001 // 1
or
00000010 // 2
&
00000001 // 1
========
00000000 // 0
As there is used the function putchar
then this integer value is required to be converted to character.
putchar((a >> i & 1) + '0');
That is '0' + 0
gives the character '0'
and '0' + 1
gives the character '1'
.
Upvotes: 3