Viapacific
Viapacific

Reputation: 45

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?

Upvotes: 0

Views: 244

Answers (2)

Weather Vane
Weather Vane

Reputation: 34585

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

Upvotes: 1

goodvibration
goodvibration

Reputation: 6206

The compiler interprets prefix 0 as base 8.

So 177(8) = 127(10) = 1111111(2).

That's your 7 bits right there.

Upvotes: 0

Related Questions