Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>From <a href="http://bytes.com/forum/thread847594.html" rel="nofollow noreferrer">Here</a> (General answer to get this thread started)</p> <p>A bit mask is a value (which may be stored in a variable) that enables you to isolate a specific set of bits within an integer type.</p> <p>Normally the masked will have the bits you are interested in set to 1 and all the other bits set to 0. The mask then allows you to isolate the value of the bits, clear all the bits or set all the bits or set a new value to the bits.</p> <p>Masks (particularly multi-bit ones) often have an associated shift value which is the amount the bits need shifting left so that the least significant masked bit is shifted to the least significant bit in the type.</p> <p>For example using a 16 bit short data type suppose you wanted to be able to mask bits 3, 4 and 5 (LSB is number 0). You mask and shift would look something like</p> <pre><code>#define MASK 0x0038 #define SHIFT 3 </code></pre> <p>Masks are often assigned in hexadecimal because it is easier to work with bits in the data type in that base as opposed to decimal. Historically octal has also been used for bit masks.</p> <p>If I have a variable, var, that contains data that the mask is relevant to then I can isolate the bits like this</p> <pre><code>var &amp; MASK </code></pre> <p>I can isolate all the other bits like this</p> <pre><code>var &amp; ~MASK </code></pre> <p>I can clear the bits like this</p> <pre><code>var &amp;= ~MASK; </code></pre> <p>I can clear all the other bits like this</p> <pre><code>var &amp;= MASK; </code></pre> <p>I can set all the bits like this</p> <pre><code>var |= MASK; </code></pre> <p>I can set all the other bits like this</p> <pre><code>var |= ~MASK; </code></pre> <p>I can extract the decimal value of the bits like this</p> <pre><code>(var &amp; MASK) &gt;&gt; SHIFT </code></pre> <p>I can assign a new value to the bits like this</p> <pre><code>var &amp;= ~MASK; var |= (newValue &lt;&lt; SHIFT) &amp; MASK; </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