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.
-
3read this stackoverflow.com/questions/10804852/…lakshman– lakshman2013-05-31 07:39:00 +00:00Commented May 31, 2013 at 7: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– coffee2013-05-31 07:47:13 +00:00Commented May 31, 2013 at 7: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– Peter Lawrey2013-05-31 08:06:33 +00:00Commented May 31, 2013 at 8:06
-
oh, thank you very much, I want to create little-endian.coffee– coffee2013-05-31 08:14:02 +00:00Commented May 31, 2013 at 8:14
2 Answers
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]);
}
3 Comments
>>>