0

Is there any way to do a kind of static cast between an int[] and byte[] ?

What i want is just to get a reference to the int[] as a byte[] without making any numeric conversions between them and, if it is possible, without having to make a copy.

0

3 Answers 3

2

Is there any way to do a kind of static cast between an int[] and byte[] ?

Short answer, no.

But you could wrap the byte[] in a ByteBuffer and get anIntBuffer from it, or just use its getInt()/putInt() methods.

In many cases, this would meet your requirements, even if not exactly what you ask for.

Something like:

byte[] bytes ...;
ByteBuffer buffer = ByteBuffer.wrap(bytes); // No copy, changes are reflected

int foo = buffer.getInt(0); // get int value from buffer

foo *= 2; 
buffer.putInt(0, foo); // write int value to buffer

// Or perhaps 
IntBuffer intBuffer = buffer.asIntBuffer(); // Creates an int "view" (no copy)
int bar = intBuffer.get(0);
intBuffer.set(0, bar);

The byte order of the byte buffer when working with multi-byte values, like int can be controlled using:

buffer.order(ByteOrder.BIG_ENDIAN); // Default is platform specific, I believe
Sign up to request clarification or add additional context in comments.

Comments

0

They are different kinds of objects who can't be cast the way you want. Neither is a subtype of the other. You have 2 different classes (not primitives).

Comments

0

Your question is unclear, what do you want to do with data that doesn't fit?

One approach would be to create a utility class that lets you treat it that way.

i.e. :

public class ByteWrapper {
    int[] data;

    byte get(int i) {
       return (byte)data[i];
    }
}

1 Comment

The problem is that i'm using legacy code that uses int[] to actually store bytes. For the application that is not a problem since it directly writes the int[] to disk with a FileOutputStream.

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.