cwhile-loopbit-manipulationunsigned-charbitwise-and

Why do I need to Bitwise AND with 1 the shift righted char in binary to get the correct binary value?


This is the exercise that I'm doing:

Assignment name : print_bits

Expected files : print_bits.c Allowed functions: write

Write a function that takes a byte, and prints it in binary WITHOUT A NEWLINE AT THE END. Your function must be declared as follows:

void print_bits(unsigned char octet);

Example, if you pass 2 to print_bits, it will print "00000010"

/////////////////////////////////////////////////////////////////////////////////////////////

This is a solution:

#include <unistd.h>

void    print_bits(unsigned char octet)
{
        int             i;
        unsigned char   bits;

        i = 8;
        while (i--)
        {
                bits = (octet >> i & 1) + '0';
                write(1, &bits, 1);
        }
}

I understand the solution, except for one part. If I right shift the char in its binary form, why do I need to perform a Bitwise AND with 1?? What would be the difference? I supposedly should get the same solution, since I'm performing the operation always with the 1 at the final bit of 1. If the bit from the unsigned char is 0, I'll get 0. If it's 1, I'll get 1. But if I try to run the program with an example without the Bitwise AND operation, I get way beyond 0 and 1. Why?


Solution

  • The right-shift operation, denoted with >>, does not just take one bit from the left operand and shift it. It shifts all the bits of the left operand. For example, given 110110012 shifted right four bits, the result is 11012. If you do not AND that with 1, the result is 13 (11012). If you do AND it with 1, the result is 1.

    In C implementations using ASCII, the character “0” has code 48, and, if you add 13 to '0', you will get 61, the code for “=”.