Wednesday, January 20, 2010

11.2.3 MASKING

Masking is a process in which a given bit pattern is transformed into another bit pattern by means of a logical bitwise operation.The original bit pattern is one of the operands in the bitwise operation.The second operand called the mask, is a specially selected bit pattern that brings about the desired transformation.

There are several kinds of masking operations.For example, a portion of a given bit pattern can be copied to a new word, while the remainder of the new word is filled with 0s.Thus, part of the original bit pattern will be "masked off" from the final result. The bitwise and operator is used (&) is used for this type of masking operation as illustrated below.

Suppose a is an unsigned integer variable whose value is 0x6db7.Extract the rightmost 6 bits of this value and assign them to the unsigned integer variable b. Assign 0s to the 10 leftmost bits of b.

To carry out this operation, we write the bitwise expression
b= a & 0x3f;

The second operand 0x3f will serve as the mask. Thus the resulting value of b will be 0x37.

The validity of this result can be established by examining the corresponding bit patterns.

             a = 0110 1101 1011 0111
       mask = 0000 0000 0011 1111
                  ---------------------------------
             b = 0000 0000 0011 0111
               = 0x37
The mask prevents the leftmost 10 bits from being copied from a to b.

Suppose once again a is an unsigned integer variable whose value is 0x6db7.Now extract the leftmost 6 bits of this value and assign them to the unsigned integer variable b.Assign 0s to the 10 rightmost bits of b.

To carry out this operation, we write the bitwise expression
b= a & 0xfc00;

Another type of masking allows a portion of a given bit pattern to be copied to a new word, while the remainder of the new word is filled with 1s.The bitwise or (|) operator is used for this purpose.

A portion of a given bit pattern can be copied to a new word, while the remainder of the original bit pattern is inverted within the new word.The bitwise exclusive or (^) operator is used for this type of masking.

No comments:

Post a Comment