0

I am working with audio, I saved audio data on short array. I want to convert it to a byte array to store the wav file. I don't know convert short[] to byte[]. Can you help me. Thank you very much.

coffee
  • 23
  • 1
  • 7
  • 3
    read this http://stackoverflow.com/questions/10804852/how-to-convert-short-array-to-byte-array – lakshman May 31 '13 at 07:39
  • thank you very much. I will try this code: private byte[] shortArrayToByteArray(short[] shortArr) { int index; int iterations = shortArr.length; ByteBuffer bb = ByteBuffer.allocate(shortArr.length * 2); for(index = 0; index != iterations; ++index){ bb.putShort(shortArr[index]); } return bb.array(); } – coffee May 31 '13 at 07:47
  • If you use ByteBuffer, make sure the byte order is correct for your system. The default is big endian, but many formats use little endian. – Peter Lawrey May 31 '13 at 08:06
  • oh, thank you very much, I want to create little-endian. – coffee May 31 '13 at 08:14

2 Answers2

2

short is 16 bit type and byte is 8 bit type . So from a n length short array you will get a 2n length byte array.

The Basics

before converting an array thing about converting a single short to byte. so as per above line you will create 2 byte from a single short.

The principle will be store first 8 bits two a byte and store second 8 bits to another short. The code will be like this

byte b1, b2;
short s;

b1 = s & 0xff;
b2 = (s >> 8) & 0xff;

Now Array

use the above principal for array now. say the array size of short is n. let the short is s

byte result[2*n];
for(int i = 0; i<2*n ; i=i+2){
    b[i]   = s[i>>1] & 0xff;
    b[i+1] = (s[i>>1 | 1] >> 8) & 0xff;
}

Using ByteBuffer class

you can also convert short array to bytearray using ByteBuffer class.

ByteBuffer byteBuf = ByteBuffer.allocate(2*n);
for(int i = 0; i<n ; i++) {
    byteBuf.putShort(buffer[i]);
}
stinepike
  • 54,068
  • 14
  • 92
  • 112
0

The only way is to create a byte array of the same size as the short array and copy the short array elements

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275