title: Bit Masking in a Cache
body: <p>In C I am attempting to separate an integer address value into the tag bit and the set index bit in a direct mapped cache with 4 sets. I do this so I can compare the correct tags at the line in the correct set of my cache. Here for example the address parameters: </p>
  
  <ul>
  <li>number of set index bits s=2 </li>
  <li>number of offset bits b=3</li>
  <li>total number of address bits m=8</li>
  </ul>
  
  <p>And in my example the address integer is 40 -- int address = 40. </p>
  
  <ul>
  <li>40 in binary is 00101000</li>
  <li>The set index should be 01 = 1</li>
  <li>The tag should be 001 = 1</li>
  </ul>
  
  <p>Instead for the tag I am getting 2 and the set index is 8 which have to be wrong because I only have 4 sets in my cache.</p>
  
  <p>Here is how I am doing it, I am bit-masking the address to get the tag, which are the bits to the left of the set index up to the m=8 bit. And the set index is between the tag and offset bits which is the 01 in the middle of the 8 bit sequence.</p>
  
  <ul>
  <li>int tag = ((address &amp; ~0 &lt;&lt; (s + b)) >> 4)</li>
  <li>int set = (address &amp; (~(~0 &lt;&lt; s) &lt;&lt; b))</li>
  </ul>
  
  <p>I know I must be wrong but the more I try to write a mask the more I am getting confused and I must be forgetting something. I at least thought I was getting the tag right because the left bits should be easier than getting middle bits. Any advice or help would be greatly appreciated thanks a lot!</p>