gpt4 book ai didi

java - 从 ByteBuffer 中移除前 n 个字节

转载 作者:行者123 更新时间:2023-11-29 07:55:31 25 4
gpt4 key购买 nike

如何在不改变或降低容量的情况下从 ByteBuffer 中删除前 n 个字节?结果应该是第 0 个字节是 n+1 字节。 Java 中是否有更好的数据类型来执行此类操作?

最佳答案

你可以尝试这样的事情:

public void removeBytesFromStart(ByteBuffer bf, int n) {
int index = 0;
for(int i = n; i < bf.position(); i++) {
bf.put(index++, bf.get(i));
bf.put(i, (byte)0);
}
bf.position(index);
}

或者像这样:

public void removeBytesFromStart2(ByteBuffer bf, int n) {
int index = 0;
for(int i = n; i < bf.limit(); i++) {
bf.put(index++, bf.get(i));
bf.put(i, (byte)0);
}
bf.position(bf.position()-n);
}

这使用绝对 getput ByteBuffer 的方法类并设置 position在下一个写入位置。

请注意绝对put方法是可选的,这意味着扩展抽象类ByteBuffer的类可能不会为其提供实现,例如它可能抛出ReadOnlyBufferException

是否选择循环到position或直到 limit取决于您如何使用缓冲区,例如,如果您手动设置 position你可能想使用循环直到 limit。如果你不这样做,那么循环直到 position 就足够了,而且效率更高。

这里是一些测试:

@Test
public void removeBytesFromStart() {
ByteBuffer bf = ByteBuffer.allocate(16);
int expectedCapacity = bf.capacity();
bf.put("abcdefg".getBytes());

ByteBuffer expected = ByteBuffer.allocate(16);
expected.put("defg".getBytes());

removeBytesFromStart(bf, 3);

Assert.assertEquals(expectedCapacity, bf.capacity());
Assert.assertEquals(0, bf.compareTo(expected));
}

@Test
public void removeBytesFromStartInt() {
ByteBuffer bf = ByteBuffer.allocate(16);
int expectedCapacity = bf.capacity();
bf.putInt(1);
bf.putInt(2);
bf.putInt(3);
bf.putInt(4);

ByteBuffer expected = ByteBuffer.allocate(16);
expected.putInt(2);
expected.putInt(3);
expected.putInt(4);

removeBytesFromStart2(bf, 4);

Assert.assertEquals(expectedCapacity, bf.capacity());
Assert.assertEquals(0, bf.compareTo(expected));
}

关于java - 从 ByteBuffer 中移除前 n 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18031927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com