<p>In converting from short to a byte array I found the following solution on the web but could not quite understand the logic involved.</p>

<pre><code>//buffer is an array of bytes, bytes[]
buffer[position] = (byte)(sample &amp; 0xff);
buffer[position+1] = (byte)((sample &gt;&gt; 8) &amp; 0xff);
</code></pre>

<p>Can someone tell me why 0xff (256) is being anded to the sample which is a short? </p>

This code probably comes from C code (or was written by a C programmer who don't parse Java as well as erickson does). This is because in Java a cast from a type with more information to a type with less information will discard the higher order bits and thus the & 0xff is unnecessary in both cases.
A short has 16 bits, two bytes. So it needs to take two slots in the byte array, because if we just casted a short into a byte one byte would be lost.
So, the code you have does
```
```
1110001100001111 sample
0000000011111111 0xff
0000000000001111 sample & 0xff => first byte`
```
```
Then, displaces the sample to get the second byte
```
```
0000000011100011 sample >> 8
0000000011111111 0xff
0000000011100011 (sample >> 8 ) & 0xff => second byte
```
```
Which can be a lot better written as erickson shows below (hopefully it'll be above soon).