title: byte array to short array and back again in java
body: <p>I'm having some issues taking audio data stored in a byte array, converting it to a big-endian short array, encoding it, then changing it back into a byte array. Here is what I have. The original audio data is stored in audioBytes2. I am using the same format for decode with a minus on the cos function instead. Unfortunately, changing the byte and short data types is non-negotiable.</p>
  
  <pre><code>    short[] audioData = null;
      int nlengthInSamples = audioBytes2.length / 2;
      audioData = new short[nlengthInSamples];
  
      for (int i = 0; i &lt; nlengthInSamples; i++) {
         short MSB = (short) audioBytes2[2*i+1];
         short LSB = (short) audioBytes2[2*i];
         audioData[i] = (short) (MSB &lt;&lt; 8 | (255 &amp; LSB));
      }
  
      int i = 0;
      while (i &lt; audioData.length) {
          audioData[i] = (short)(audioData[i] + (short)5*Math.cos(2*Math.PI*i/(((Number)EncodeBox.getValue()).intValue())));
          i++;
      }
  
      short x = 0;
      i = 0;
      while (i &lt; audioData.length) {
          x = audioData[i];
          audioBytes2[2*i+1] = (byte)(x &gt;&gt;&gt; 0);
          audioBytes2[2*i] = (byte)(x &gt;&gt;&gt; 8);
          i++;
      }
  </code></pre>
  
  <p>I have done everything that I can think of to make this work, but the closest I've come is getting it to work every other encode/decode and I have no idea why. Thanks for any help.</p>