Search code examples
javashortbytearrayoutputstream

ByteArrayOutputStream for shorts instead of bytes


I have used the ByteArrayOutputStream which is very useful but for my needs the limits are too great (ie I am dealing with numbers in the range +-32,768)

Here is the code where I would use it:

ByteArrayOutputStream leftStream = new ByteArrayOutputStream();
ByteArrayOutputStream rightStream = new ByteArrayOutputStream();

while (din.read(temp, 0, 4) != -1) {
    if (decodedFormat.getChannels() == 2) {
       leftStream.write(temp[1] * 256 + temp[0]);
       rightStream.write(temp[3] * 256 + temp[2]);
    }
}

byte[] left = leftStream.toByteArray();
byte[] right = rightStream.toByteArray();

However the ByteArrayInputStream does not allow for values over 127 or under 128. Is there an equivalent ShortArrayOutputStream that allows shorts? Or do I have to make one myself somehow?


Solution

  • Yes, Use the DataOutputStream:

    ByteArrayOuputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    
    dos.writeShort(val);
    

    This works even on embedded java devices with low java version 1.3

    To read in use:

    ByteArrayInputStream and DataInputStream dis, and dis.readShort():

    ...
    byte[] bytes = bos.toByteArray();
    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    DataInputStream dis = new DataInputStream(bis);
    short val = dis.readShort();