Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a byte[] to short[] in Java [duplicate]

Tags:

java

Possible Duplicate:
byte array to short array and back again in java

the encodeAudio() method in Xuggler has the following parameters:

  • int streamIndes
  • short[] samples
  • long timeStamp
  • TimeUnit unit

  • Using TargetDataLine from javax.sound.sampled I can read the data into a byte[] array
    byte[] tempBuffer = new byte[10000];
    fromMic.read(tempBuffer,0,tempBuffer.length);
    

    But the problem is that the samples argument needs short[]

    like image 215
    An SO User Avatar asked Dec 25 '12 18:12

    An SO User


    1 Answers

    You are lucky enough that byte is "fully castable" to short, so:

    // Grab size of the byte array, create an array of shorts of the same size
    int size = byteArray.length;
    short[] shortArray = new short[size];
    
    for (int index = 0; index < size; index++)
        shortArray[index] = (short) byteArray[index];
    

    And then use shortArray.

    Note: as far as primitive type goes, Java always treats them in big endian order, so converting, say, byte ff will yield short 00ff.

    like image 168
    fge Avatar answered Oct 03 '22 10:10

    fge