0

I am having issues trying to add multiple byte arrays to one. I am not talking about concatenating here. I need to add individual items of the Byte[]. This is what i am looking for.

    byte[] one = [4,5,6];
    byte[] two = [1,2,1];

The result should be

    byte[] sum = [5,7,7];

This is just a simple example. I am writing my own algorithm to mix different pcm recordings in android. This is where i am stuck at. any help would be much appreciated.

UPDATE:

Here is my code snippet:

while(stream[1].read()!=-1) {   
List<byte[]> arrayColl = new ArrayList<byte[]>();
for(int i =0; i<recfiles.length; i++) {
stream[i].read(buffer);
arrayColl.add(buffer);
}
}

There can be multiple stream based on users selection. The loop above will read multiple streams in a buffer and that buffer is added to an ArrayList. Now what i need to do is to mix the bytes in the arraylist in a way i mentioned above. The buffer is a byte[]

2 Answers 2

1

To add multiple byte arrays, you need to loop through each one, adding the result to an accumulator array:

public byte[] sum(byte[]... arrays) {
    // optional: check that arrays.length > 0 (at least one array was passed)
    final int len = arrays[0].length;
    final byte[] result = new byte[len];
    for (byte[] array : arrays) {
        // optional: test that array has length len
        for (int i = 0; i < len; ++i) {
            result[i] += array[i];
        }
    }
    return result;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ted! With these two answers. I should be able to solve my issue.
0

What you're looking for is a simple matrix addition. You can accomplish this with a for loop by iterating over the domain of the loop's subscript operator (namely, from 0 to the length of the array) as follows:

int length = Math.min(one.length, two.length);
byte[] sum = new byte[length];
for (int i = 0; i<length; i++) {
    sum[i] = one[i] + two[i];
}

Alternatively, if you want to ensure that the two arrays are of the same size, you could use:

if (one.length != two.length) {
    throw new IllegalArgumentException("unequal lengths");
}
int length = one.length; // or two.length
byte[] sum = new byte[length];
for (int i = 0; i<length; i++) {
    sum[i] = one[i] + two[i];
}

3 Comments

Hi WChargin, thanks for the quick response. Seems like this is exactly right. I need one more suggestion. The algorithm i am working on mixes multiple files depending on the users selection. How can we tweak this to work with multiple byte[] not just two.
What do you mean to work with multiple byte[]s? Could you give an example?
Hi WChargin, I have added a code snippet which will give you the picture of what i am tring to do.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.