3

I have an ByteArrayOutputStream connected with a Dataline from an AudioSource. I need to convert the Stream in some significative values that probally are the sound values taken from source or not ? Well then how can I conver the byteArray (from ByteArrayOutStream.getByteArray()) in a intArray?. I googled it but with no luck .

p.s. the audioFormat that I used is : PCM_SIGNED 192.0Hz 16Bit big endian

1
  • what do you need the conversion from an byte array to an int array for? Commented May 2, 2011 at 18:00

3 Answers 3

7

Use a ByteBuffer. You can convert not only to different array types this way, but also deal with endian issues.

Sign up to request clarification or add additional context in comments.

Comments

3

You can try the following:

ByteBuffer.wrap(byteArray).asIntBuffer().array()

2 Comments

UnsupportedOperationException
1

When you do ByteArrayOutStream.toByteArray(), you get: byte[]. So now, I assume you need to convert byte[] to int.

You can do this:

/**
 * Convert the byte array to an int.
 *
 * @param b The byte array
 * @return The integer
 */
public static int byteArrayToInt(byte[] b) {
    return byteArrayToInt(b, 0);
}

/**
 * Convert the byte array to an int starting from the given offset.
 *
 * @param b The byte array
 * @param offset The array offset
 * @return The integer
 */
public static int byteArrayToInt(byte[] b, int offset) {
    int value = 0;
    for (int i = 0; i < 4; i++) {
        int shift = (4 - 1 - i) * 8;
        value += (b[i + offset] & 0x000000FF) << shift;
    }
    return value;
}

2 Comments

for (int i = 0; i < 4; i++) { int shift = (4 - 1 - i) * 8; value += (b[i + offset] & 0x000000FF) << shift; } i dont understand this code ... i<4 means that 1 byte is maked by 4 bit ?
No an integer is 4 bytes so you just add one byte after the other at the correct position - although personally I wouldn't use an add to do that, that works fine too (minimally slower but if you don't call the function billion of times that's hardly important). Anyways use of a ByteBuffer should be preferred. Also note that doesn't take endianness into account.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.