将 Java 中的字节数组转换为 int 数组,通过 ByteBuffer 到 IntBuffer,不截断

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

这里还有其他关于此主题的问题,其中大部分涉及 ByteBufferasIntBuffer。但是,我还没有看到任何关于在转换为 IntBuffer.

时如何防止值被截断的解释

示例:

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();

我有一个 RC4 加密算法,它采用 int[] 类型的明文参数。因此,我需要将明文转换为 int[]ByteBuffer 的问题和 asIntBuffer 的使用是明文被截断,因为限制是独立的(在我的例子中从 11 到 2)。

要么我做错了什么,要么 ByteBuffer 不适合这里。

如有任何帮助,我们将不胜感激。谢谢。

您好,如果您不需要使用 IntBuffer,可以试试这个。

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

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

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

你基本上直接将字节转换为整数。

使用 Buffer#array 不适合您的需要。文档说

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

您在代码中使用了两个缓冲区。第一个是 ByteBuffer ,它包装了一个数组。因此,此 Buffer 由一个数组支持,并且对 #array() 的调用是有效的。您通过 #asIntBuffer() 创建的第二个。此缓冲区只是第一个缓冲区的 viewnot 由数组支持。所以你在调用 array().

时看到了 UnsupportedOperationException

您想加密 byte[],但您的算法适用于 int[]。那么 Jawad 的答案就是你要走的路。