Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 “=”.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading