Search code examples
ckernighan-and-ritchie

Can`t comprehend the bitwise operations


Reading the K&R book I stumbled upon chapter 2.9 which describes bitwise operators in C. Right in the beginning there is this claim:

The bitwise AND operator & is often used to mask off some set of bits, for example n = n & 0177; sets to zero all but the low-order 7 bits of n.

I am a bit confused with the true meaning of it. How does hexadecimal (if i got it right) 0177 represent low-order 7 bits? I tried to test it in code and below is what I did:

#include <stdio.h>

int main()
{
    int n = 1490;
    n = n & 0177;
    printf("%i\n", n);
}

The output of the code is 82. Converting 1490 to binary I got 10111010010 and after setting all bits to zero apart from 7 low order bits i ended up with 1010010 which really equals 82 in decimal. Trying to understand the logic under the hood I applied &(AND) operator manually but it resulted in a completely different number. What I am doing wrong?


Solution

  • Please be aware that 0177 is not hexadecimal but the octal form of binary 01111111. Each octal digit represent 3 bits, and the leading 0 tells the compiler to interpret it that way.

    So the operation is

    decimal 1490    10111010010
    octal   0177    00001111111
                AND -----------
    decimal 82      00001010010