这里还发布了有关此主题的其他问题,其中大部分涉及 ByteBuffer
和 asIntBuffer
。但是,我还没有看到任何关于如何在转换为 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];
}
您基本上将字节直接转换为整数。
关于java - Java中将字节数组转换为int数组,通过ByteBuffer到IntBuffer,不截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33351480/