title: Faster way to apply a bit mask while working with strings and shorts?
body: <p>I have the following bit of code which will take in a string of words as well as a bit-mask. It will apply the mask to a certain chunk of a certain word (as specified by startWord, highBit and length) and then return a true or false value if the mask matches.</p>
  
  <p>It works, but it's not very quick. Surely there's a way of doing it better?</p>
  
  <p>EDIT:</p>
  
  <p>To clarify, highBit and length are used to shorten the length of the word. So if we have a word that is dec: 37, then the binary is 0b100101. If it has a high bit of 2 and a length of two, then we only care about applying the mask to the last two digits (01). If it had a high bit of 3 and a length of 2, then it would be the digits in the square brackets: 0b100[10]1 etc.</p>
  
  <p>It's effectively checking that any bit that is set in the mask is also set in the corresponding word at the corresponding position.</p>
  
  <p>Further Edit:</p>
  
  <p>If we have word 37 (0b100101) and a mask of (0b1), and we're interested in the entire word (so high bit is 15, and length is 16) then this will evaluate true. If the mask is 0b0 then it will also evaluate true (We are just looking for bits that are set).</p>
  
  <p>The mask should always be greater in length than the "length" of the section of the word being analysed.</p>
  
  <pre><code>  public bool AddMask(string maintMessage, short mask, int startWord, int highBit, int length)
      {            
          // Maintenance message is a string of decimal 16-bit values 
          // seperated by semi-colons.
          var splitMsg = maintMessage.Split(';');
          var word = splitMsg[startWord];
          return AddMask(short.Parse(word), mask, highBit, length);            
      }
  
  
      public bool AddMask(short wordToMask, short mask, int highBit, int length)
      {
  
          if (highBit &lt; length)
              length = highBit; // Or throw an exception?
  
          var binWord = Convert.ToString(wordToMask, 2);
          if (length &gt; binWord.Length) // Shorten 'length' to max possible length
              length = binWord.Length;
  
          binWord = binWord.Substring(binWord.Length - highBit, length);
  
          var shortWord = Convert.ToInt16(binWord, 2);
  
          var result = shortWord &amp; mask;
          return result == mask;
      }
  </code></pre>