Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm going to be more explicit here because I think bitwise masks are a great tool that should be in any devs belt. I'm going to try to expand on the answers above. First, an example of using an integer to maintain state flags (common usage):</p> <pre><code>// These are my masks private static final int MASK_DID_HOMEWORK = 0x0001; private static final int MASK_ATE_DINNER = 0x0002; private static final int MASK_SLEPT_WELL = 0x0004; // This is my current state private int m_nCurState; </code></pre> <p>To <strong><em>set</em></strong> my state, I use the bitwise OR operator:</p> <pre><code>// Set state for'ate dinner' and 'slept well' to 'on' m_nCurState = m_nCurState | (MASK_ATE_DINNER | MASK_SLEPT_WELL); </code></pre> <p>Notice how I 'or' my current state in with the states that I want to turn 'on'. Who knows what my current state is and I don't want to blow it away. </p> <p>To <strong><em>unset</em></strong> my state, I use the bitwise AND operator with the complement operator:</p> <pre><code>// Turn off the 'ate dinner' flag m_nCurState = (m_nCurState &amp; ~MASK_ATE_DINNER); </code></pre> <p>To <strong><em>check</em></strong> my current state, I use the AND operator:</p> <pre><code>// Check if I did my homework if (0 != (m_nCurState &amp; MASK_DID_HOMEWORK)) { // yep } else { // nope... } </code></pre> <p>Why do I think this is interesting? Say I'm designing an interface that sets my state. I could write a method that accepts three booleans:</p> <pre><code>void setState( boolean bDidHomework, boolean bAteDinner, boolean bSleptWell); </code></pre> <p>Or, I could use a single number to represent all three states and pass a single value:</p> <pre><code>void setState( int nStateBits); </code></pre> <p>If you choose the second pattern you'll be very happy when decide to add another state - you won't have to break existing impls of your interface.</p> <p>My two cents. Thanks.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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