简体   繁体   English

在Java中将字节数组通过ByteBuffer转换为IntBuffer,而不会截断

[英]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 . 在此主题上还有其他问题,其中大多数涉及ByteBufferasIntBuffer However, I have not seen any explaination on how to keep the value from truncating when converting to an IntBuffer . 但是,我还没有看到任何关于如何在转换为IntBuffer时如何防止该值被截断的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[] . 我有一个RC4加密算法,该算法采用int[]类型的纯文本参数。 Hence, I need to convert the plaintext into int[] . 因此,我需要将纯文本转换为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). ByteBufferasIntBuffer的使用问题是明文被截断了,因为限制是独立的(在我的示例中为11到2)。

Either I'm doing something wrong or ByteBuffer is not the way to go here. 我做错了什么,或者ByteBuffer不在这里。

Any help would be appreciated. 任何帮助,将不胜感激。 Thank you. 谢谢。

Hi you can try this if you do not need to use IntBuffer. 嗨,如果您不需要使用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. 您基本上可以将字节直接转换为整数。

Using Buffer#array is not suitable for your needs. 使用Buffer#array不适合您的需求。 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 ReadOnlyBufferException-如果此缓冲区由数组支持但为只读
UnsupportedOperationException - If this buffer is not backed by accessible array UnsupportedOperationException-如果此缓冲区不受可访问数组的支持

You are using two Buffers in your code. 您在代码中使用了两个缓冲区。 The first one is a ByteBuffer which wraps an array. 第一个是包装数组的ByteBuffer Thus this Buffer is backed by an array and a call to #array() is valid. 因此,此Buffer由数组支持,并且对#array()的调用有效。 The second one you create via #asIntBuffer() . 您通过#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() . 因此,在调用array()时会看到UnsupportedOperationException

You want to encrypt a byte[] , but your algorithm works on a int[] . 您想加密一个byte[] ,但是您的算法在int[] Then Jawad answer is your way to go. 那么Jawad的答案就是您要走的路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM