Reputation: 27203
I am reading The C Programming Language by Brian Kernigan and Dennis Ritchie. Here is what it says about the bitwise AND operator:
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 don't quite see how it is masking the lower seven order bits of n
. Please can somebody clarify?
Upvotes: 32
Views: 9367
Reputation: 391
0177 is an octal value. In octal, each digit is represented by 3 bits from the value 000 to 111. So, 0177 translates to 001111111 (i.e. 001|111|111). This number in 32 bit binary (can be 64 bit too except you need to sign-extend, which will be all 0s in this case) is 00000000000000000000000001111111
(00|000|000|000|000|000|000|000|001|111|111).
Performing a bitwise AND
(symbolically, &
) with it for a given number will output the lower 7 bits of the number, turning of rest of the digits in the n-bit number to 0.
(since x&0 =0 & x&1=x e.g 0&0=0 ,1&0=0, 1&1=1 0&1=1)
Upvotes: 0
Reputation: 726809
The number 0177
is an octal number representing the binary pattern below:
0000000001111111
When you AND
it using the bitwise operation &
, the result keeps the bits of the original only in the bits that are set to 1
in the "mask"; all other bits become zero. This is because "AND" follows this rule:
X & 0 -> 0 for any value of X
X & 1 -> X for any value of X
For example, if you AND
0177
and 0545454
, you get
0000000001111111 -- 0000177
0101010101010101 -- 0545454
---------------- -------
0000000001010101 -- 0000154
Upvotes: 37
Reputation: 11612
It is already explained that the first '0' used for octal representation of a number in ANSI C. Actually, the number 0177 (octal) is same with 127 (in decimal), which is 128-1 and also can be represented as 2^7-1
, and 2^n-1
in binary representation means take n 1's and put all the 1's to the right.
0177 = 127 = 128-1
which is a bitmask;
0000000000000000000000001111111
You can check the code down below;
#include <stdio.h>
int main()
{
int n = 0177; // octal representation of 127
printf("Decimal:[%d] : Octal:[%o]\n", n, n, n);
n = 127; // decimal representation of 127
printf("Decimal:[%d] : Octal:[%o]\n", n, n, n);
return 0;
}
Decimal:[127] : Octal:[177]
Decimal:[127] : Octal:[177]
Upvotes: 4
Reputation: 158529
Since 0177
is an octal literal and each octal number is 3
three bits you have, the following binary equivalents:
7 = 111
1 = 001
Which means 0177
is 001111111
in binary.
Upvotes: 5
Reputation: 145899
In C an integer literal prefixed with 0
is an octal number so 0177
is an octal number.
Each octal digit (of value 0
to 7
) is represented with 3 bits and 7
is the greatest value for each digit. So a value of 7
in octal means 3
bits set.
Upvotes: 6