Home > Enterprise >  Return byte[] by reference with System.arraycopy in Java
Return byte[] by reference with System.arraycopy in Java

Time:01-08

I am trying to return a byte array in a function parameter by reference. Here is my code:

@Override
public int exampleFunction(byte[] inputData, int inputDataSize, byte[] outputData) {
        synchronized (mutex) {
                try {
                    byte[] received = Codec2Link.codec2Decode(inputData, inputData.length); //Returns byte array of length 640
                    if (received.length == 640) {
                        byte[] upperBytes = ByteUtils.convertUpper(received); //Returns byte array of length 1280
                        System.arraycopy(upperBytes, 0, outputData, 0, upperBytes.length);
                    } else
                        System.out.println("Failed!");
                } catch (Exception ex) {
                    System.out.println("Error in Java!");
                    ex.printStackTrace();
                }

            return 1280;
        }
    }

My question, is it possible to pass the value in outputData by System.arraycopy? I have already tried. It gave me "java.lang.ArrayIndexOutOfBoundsException" at the time of System.arraycopy. What am I doing wrong here?

CodePudding user response:

I tried to reproduce your error with this code, but there is no exception

import org.junit.jupiter.api.Test;

public class ByteArray {

    public byte[] exampleFunction() {
        byte[] inputData = {0, 1, 2, 3, 4, 5, 6, 7};
        byte[] outputData = new byte[8];
        System.arraycopy(inputData, 0, outputData, 0, inputData.length);
        return outputData;
    }

    @Test
    public void test() {
        byte[] byteArray = exampleFunction();
        for (int i = 0; i < byteArray.length; i  ) {
            System.out.println(byteArray[i]);
        }
    }
}

I don't know what Codec2Link.codec2Decode does. If you provide an executable version of your code it would be easier to help.

  • Related