在 Java 中切片字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18367539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:55:02  来源:igfitidea点击:

Slicing byte arrays in Java

java

提问by Eric

I'm trying to slice a byte array to prune the first part of the array. I'm using ByteBuffer but it does not behave like I would expect.

我正在尝试对字节数组进行切片以修剪数组的第一部分。我正在使用 ByteBuffer 但它的行为不像我期望的那样。

byte[] myArray = new byte[10];
ByteBuffer buf = ByteBuffer.wrap(myArray);
buf.position(5);
ByteBuffer slicedBuf = buf.slice();
byte[] newArray = slicedBuf.array();

I would expect the size of newArray to be 5, containing only the last portion of my ByteBuffer. Instead, the full byte array is returned. I understand that this is because the "backing buffer" is the same all along.

我希望 newArray 的大小为 5,仅包含我的 ByteBuffer 的最后一部分。而是返回完整的字节数组。我知道这是因为“后备缓冲区”一直都是一样的。

How can I slice to have only the desired part of the array?

如何切片以仅包含数组的所需部分?

EDIT: Added context

编辑:添加上下文

The bytes are received from network. The buffer is formed like this :

从网络接收字节。缓冲区是这样形成的:

[ SHA1 hash ] [ data... lots of it ]

[ SHA1 hash ] [ data... lots of it ]

I already have a function that takes a byte array as a parameter and calculate the SHA1 hash. What I want is to slice the full buffer to pass only the data without the expected hash.

我已经有一个将字节数组作为参数并计算 SHA1 哈希的函数。我想要的是切片完整缓冲区以仅传递没有预期散列的数据。

采纳答案by Joni

You can use the Arrays.copyOfRangemethod. For example:

您可以使用该Arrays.copyOfRange方法。例如:

// slice from index 5 to index 9
byte[] slice = Arrays.copyOfRange(myArray, 5, 10);

回答by Brian Roach

The ByteBufferyou created is being backed by that array. When you call slice()you effectively receive a specific viewof that data:

ByteBuffer您创建正在由数组支持。当您打电话时,slice()您会有效地收到该数据的特定视图

Creates a new byte buffer whose content is a shared subsequence of this buffer's content.

创建一个新的字节缓冲区,其内容是此缓冲区内容的共享子序列。

So calling array()on that returned ByteBufferreturns the backing array in its entirety.

因此调用array()返回的ByteBuffer返回整个后备数组。

To extract all the bytes from that view, you could do:

要从该视图中提取所有字节,您可以执行以下操作:

byte[] bytes = new byte[slicedBuf.remaining()];
slicedBuf.read(bytes);

The bytes from that view would be copied to the new array.

该视图中的字节将被复制到新数组中。

Edit to add from comments below:It's worth noting that if all you're interested in doing is copying bytes from one byte[]to another byte[], there's no reason to use a ByteBuffer; simply copy the bytes.

编辑以从下面的评论中添加:值得注意的是,如果您感兴趣的只是将字节从一个复制byte[]到另一个byte[],则没有理由使用ByteBuffer; 只需复制字节。