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.

4
  • 3
    read this stackoverflow.com/questions/10804852/… Commented 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(); } Commented 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. Commented May 31, 2013 at 8:06
  • oh, thank you very much, I want to create little-endian. Commented May 31, 2013 at 8:14

2 Answers 2

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]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

You forgot about the endianness
And signedness. This will screw up your data badly, you should at least have used >>>
@icepack I used little endian for example.. the main goal of the question is not to make a byte array for him.. but to give him a concept.. Am i wrong?
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.