I am fairly new to C programming, and I encountered bit masking. Can someone explain to me the general concept and function of bit masking? Examples are much appreciated.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-
We are doing AND operation in this example. There are also other masking operators- OR, XOR.
Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-
So, only the middle 4 bits (as these bits are
1
in this mask) remain.Lets see this with XOR-
Now, the middle 4 bits are flipped (
1
became0
,0
became1
).So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-
This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-
Short Explanation: If the least significant bit of a binary number is
1
then it is odd; for0
it will be even. So, by doing AND with1
we are removing all other bits except for the least significant bit i.e.:A mask defines which bits you want to keep, and which bits you want to clear.
Masking is the act of applying a mask to a value. This is accomplished by doing:
Below is an example of extracting a subset of the bits in the value:
Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:
Masking is implemented using AND, so in C we get:
Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this,
&
, and>>
(shift right). This is how we can extract the four bytes from a 32-bit integer:Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask: