Print out binary char format
I wrote a function to print binary format char
months ago, it was like this and it worked well:
void PrnCharBit(char x)
{
int i,mask;
for(i=CHAR_BIT;i>=1;i--)
{
mask=(1<<(i-1))&x;
putchar((mask==0)?'0':'1');
}
putchar('\n');
}
And today I want to use this function, so I wrote one almost the same as above:
void PrnCharBit(char c)
{
int i;
char mask=0;
//printf("%d\n",CHAR_MAX);
for(i=sizeof(char)*CHAR_BIT-1;i>=0;i--)
{
mask=1<<i;
if(mask&c==0) putchar('0');
else putchar('1');
}
putchar('\n');
}
However, the second function didn't work. I can't figure out why, because the two functions are almost the same! Why doesn't the second function give the same result?
source to share
Precedence operator . The equality operator ( ==
) is ordered before the bitwise operation ( &
).
Clang warns the following:
& has a lower precedence than ==; == will be evaluated first
When changing the second function if(mask&c==0)
toif((mask&c)==0)
source to share