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?
The logical bitwise operators AND, OR, XOR, and NOT can be used with a mask to extract or manipulate specific bits. Binary or logical shifts can be used to move binary digits, for example, within a register. A logical bitwise operator is one that works on a single bit (or set of bits) within a binary string.
The bitwise AND may be used to clear selected bits (or flags) of a register in which each bit represents an individual Boolean state. This technique is an efficient way to store a number of Boolean values using as little memory as possible. Because 6 AND 1 is zero, 6 is divisible by two and therefore even.
The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise AND operator must have integral types.
XOR operator^, is used to controllably invert bits. NOT operator~, is used to invert all the bits in a number. Left shift operator<<, makes numbers bigger by shifting their bits to higher places.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With