2

What I am trying to do is place 4 bytes that are currently in an array into a single byte variable. For example:

public myMethod()
{
   byte[] data = {(byte) 0x03, (byte) 0x4C, (byte) 0xD6, (byte) 0x00 };
   writeData(testMethod((byte)0x4C, data));
}

public byte[] testMethod(byte location, byte[] data)
{
    byte[] response = {(byte) 0x00, (byte) 0x21, location, data);
    return response;
}

This obviously dose not work because you cannot cast byte to byte[].

Any ideas?

EDIT: There is some confusion as to what I am asking. What I am looking for is

data = (byte) 0x034CD600;

In the "testMethod".

2 Answers 2

2

You could try something like that:

private static final byte[] HEADER = new byte[] { (byte) 0x00, (byte) 0x21 };

public static byte[] testMethod(byte location, byte[] data) {
    byte[] response = Arrays.copyOf(HEADER, HEADER.length + data.length + 1);
    response[HEADER.length] = location;
    System.arraycopy(data, 0, response, HEADER.length + 1, data.length);
    return response;
}

or if you are using ByteBuffers

public static ByteBuffer testMethodBB(ByteBuffer bb, byte location, byte[] data) {
    if(bb.remaining() < HEADER.length + 1 + data.length) {
        bb.put(HEADER);
        bb.put(location);
        bb.put(data);
        bb.flip();
        return bb;
    }
    throw new IllegalStateException("Buffer overflow!");
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 I like the ByteBuffer solution. You can always return the backing array too.
0

Just create a byte[] big enough to store the elements from data.

public byte[] testMethod(byte location, byte[] data)
{
    byte[] response = new byte[3 + data.length];
    response[0] = (byte) 0x00;
    response[1] = (byte) 0x21;
    response[2] = location;
    for (int i = 0; i < data.length; i++) {
        response[3 + i] = data[i];
    }
    return response;
}

Use System.arraycopy() if speed is important. I find the above more understandable.

The notation

byte[] response = {(byte) 0x00, (byte) 0x21, location, date);

is, as you said, illegal. The {...} initializer only accepts variables or literals of type byte.

3 Comments

That works if I am trying to place the data at separate indexes. I need to place them all in the same index.
@Talls I don't understand. You cannot fit 4 bytes (32 bits) into 1 byte (8 bits).
You are correct. I misunderstood the context of the situation.

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.