Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte array to short array and back again in java

I'm having some issues taking audio data stored in a byte array, converting it to a big-endian short array, encoding it, then changing it back into a byte array. Here is what I have. The original audio data is stored in audioBytes2. I am using the same format for decode with a minus on the cos function instead. Unfortunately, changing the byte and short data types is non-negotiable.

    short[] audioData = null;     int nlengthInSamples = audioBytes2.length / 2;     audioData = new short[nlengthInSamples];      for (int i = 0; i < nlengthInSamples; i++) {        short MSB = (short) audioBytes2[2*i+1];        short LSB = (short) audioBytes2[2*i];        audioData[i] = (short) (MSB << 8 | (255 & LSB));     }      int i = 0;     while (i < audioData.length) {         audioData[i] = (short)(audioData[i] + (short)5*Math.cos(2*Math.PI*i/(((Number)EncodeBox.getValue()).intValue())));         i++;     }      short x = 0;     i = 0;     while (i < audioData.length) {         x = audioData[i];         audioBytes2[2*i+1] = (byte)(x >>> 0);         audioBytes2[2*i] = (byte)(x >>> 8);         i++;     } 

I have done everything that I can think of to make this work, but the closest I've come is getting it to work every other encode/decode and I have no idea why. Thanks for any help.

like image 594
Aaron Avatar asked Apr 11 '11 18:04

Aaron


People also ask

Can we convert byte to short?

The shortValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as short. Return Value: It returns the value of ByteObject as short.

Can we convert byte to double in Java?

Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator.

How do you copy byte array?

copyOf(byte[] original, int newLength) method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values.

Which method returns byte array of String?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument.


1 Answers

I also suggest you try ByteBuffer.

byte[] bytes = {}; short[] shorts = new short[bytes.length/2]; // to turn bytes to shorts as either big endian or little endian.  ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);  // to turn shorts back to bytes. byte[] bytes2 = new byte[shortsA.length * 2]; ByteBuffer.wrap(bytes2).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(shortsA); 
like image 71
Peter Lawrey Avatar answered Oct 12 '22 16:10

Peter Lawrey