Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this bitwise AND operator masking the lower seven order bits of the number?

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?

like image 710
Geek Avatar asked Aug 09 '13 17:08

Geek


People also ask

How bitwise logical operators are used in bit masking?

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.

What does bitwise and do to a sequence of bits?

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.

How does a Bitwise operator work?

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.

Which bitwise operation would you use if you need to invert certain bits of a binary value?

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.


2 Answers

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 
like image 155
Sergey Kalinichenko Avatar answered Sep 24 '22 23:09

Sergey Kalinichenko


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.

like image 30
ouah Avatar answered Sep 21 '22 23:09

ouah