Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A mask defines which bits you want to keep, and which bits you want to clear.</p> <p>Masking is the act of applying a mask to a value. This is accomplished by doing:</p> <ul> <li>Bitwise ANDing in order to extract a subset of the bits in the value</li> <li>Bitwise ORing in order to set a subset of the bits in the value</li> <li>Bitwise XORing in order to toggle a subset of the bits in the value</li> </ul> <p>Below is an example of extracting a subset of the bits in the value:</p> <pre><code>Mask: 00001111b Value: 01010101b </code></pre> <p>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:</p> <pre><code>Mask: 00001111b Value: 01010101b Result: 00000101b </code></pre> <p>Masking is implemented using AND, so in C we get:</p> <pre><code>uint8_t stuff(...) { uint8_t mask = 0x0f; // 00001111b uint8_t value = 0x55; // 01010101b return mask &amp; value; } </code></pre> <p>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, <code>&amp;</code>, and <code>&gt;&gt;</code> (shift right). This is how we can extract the four bytes from a 32-bit integer:</p> <pre><code>void more_stuff(uint32_t value) { // Example value: 0x01020304 uint32_t byte1 = (value &gt;&gt; 24); // 0x01020304 &gt;&gt; 24 is 0x01 so // no masking is necessary uint32_t byte2 = (value &gt;&gt; 16) &amp; 0xff; // 0x01020304 &gt;&gt; 16 is 0x0102 so // we must mask to get 0x02 uint32_t byte3 = (value &gt;&gt; 8) &amp; 0xff; // 0x01020304 &gt;&gt; 8 is 0x010203 so // we must mask to get 0x03 uint32_t byte4 = value &amp; 0xff; // here we only mask, no shifting // is necessary ... } </code></pre> <p>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:</p> <pre><code>uint32_t byte3 = (value &amp; 0xff00) &gt;&gt; 8; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload