user3621633
user3621633

Reputation: 1721

Converting byte array to int array in Java, via ByteBuffer to IntBuffer, without truncating

There are other questions posted here on this topic, most of which involve ByteBuffer and asIntBuffer. However, I have not seen any explaination on how to keep the value from truncating when converting to an IntBuffer.

Example:

byte[] plainTextBytes = "Hello World".getBytes();

// Truncates the limit from 11 to 2
IntBuffer intBuffer = ByteBuffer.wrap( plainTextBytes ).asIntBuffer();

// Results in java.lang.UnsupportedOperationException
int[] plainTextInt = intBuffer.array();

I have an RC4 encryption algorithm which takes a plaintext argument of type int[]. Hence, I need to convert the plaintext into int[]. The problem with ByteBuffer and the use of asIntBuffer is the plaintext is being truncated because the limit is independent (goes from 11 to 2, in my example).

Either I'm doing something wrong or ByteBuffer is not the way to go here.

Any help would be appreciated. Thank you.

Upvotes: 2

Views: 4017

Answers (2)

frifle
frifle

Reputation: 820

Using Buffer#array is not suitable for your needs. The documentation says

Returns the byte array that backs this buffer (optional operation).

Throws:
ReadOnlyBufferException - If this buffer is backed by an array but is read-only
UnsupportedOperationException - If this buffer is not backed by accessible array

You are using two Buffers in your code. The first one is a ByteBuffer which wraps an array. Thus this Buffer is backed by an array and a call to #array() is valid. The second one you create via #asIntBuffer(). This Buffer is only a view of the first buffer which is not backed by an array. So you see the UnsupportedOperationException when calling array().

You want to encrypt a byte[], but your algorithm works on a int[]. Then Jawad answer is your way to go.

Upvotes: 2

user5156016
user5156016

Reputation:

Hi you can try this if you do not need to use IntBuffer.

byte[] plainTextBytes = "Hello World".getBytes();

int[] ints = new int[plainTextBytes.length];

for(int i = 0; i < ints.length; i++){
    ints[i] = plainTextBytes[i];
}

You basically convert bytes directly into ints.

Upvotes: 2

Related Questions