title: Get byte - how is this wrong?
body: <p>I want to get the designated byte from a 32 bit integer. I am getting wrong values but I don't know why.</p>
  
  <p>The restrictions to this problem are:</p>
  
  <ul>
  <li>Must use signed bits, and I can't use multiplication. </li>
  <li>I specifically need to know what is wrong with the function as it's below.</li>
  </ul>
  
  <p>Here is the function:</p>
  
  <pre><code>int retrieveByteFromWord(int word, int byte)
  {
    return (word &gt;&gt; (byte &lt;&lt; 3)) &amp; 0xFF;
  } 
  </code></pre>
  
  <p>ex:
             (3)       (2)      (1)      (0)      ------ byte number
  In word: 10010011 11001100 00110011 10101000</p>
  
  <p>I want to return byte 2 (1100 1100).</p>
  
  <p><code>retrieveByteFromWord(word, 2)</code> ---- gives: 1100 1100 </p>
  
  <p>But for some cases it's wrong and it won't tell me what case.</p>
  
  <p>Any ideas?</p>
  
  <hr>
  
  <p>Here is the problem:</p>
  
  <p>You just started working for a company that is implementing a set of procedures to operate on a data structure where 4 signed bytes are packed into a 32 bit unsigned. Bytes within the word are numbered from 0(LSB) to 3(MSB). You have been assigned the task of implementing a function for a machine using 2's complement arithmetic and arithmetic right shifts with the following prototype:</p>
  
  <pre><code>typedef unsigned packed_t
  
  int xbyte(packed_t word, int bytenum);
  </code></pre>
  
  <p>This is the previous employees attempt which got him fired for being wrong:</p>
  
  <pre><code>int xbyte(packed_t word, int bytenum)
  {
    return (word &gt;&gt; (bytenum &lt;&lt; 3)) &amp; 0xFF;
  }
  </code></pre>
  
  <ul>
  <li><p>A) What is wrong with the code?</p></li>
  <li><p>B) Write a correct implementation using only left and right shifts and one subtraction.</p></li>
  </ul>
  
  <p>I have done B but still don't know why A is wrong. Is it because the decimal numbers going in like 12, 15, 19, 55 and then getting packed into a word and then when I extract them they aren't the same number anymore??? It might be so I am going to run some tests real fast...</p>