Search code examples
cbinarycharshiftbitwise-and

Why is the & 1 and + '0' is needed to display the binary number?


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');
}

Solution

  • 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'.