[英]Java Bytebuffer overwrite bytes
I've got a ByteBuffer
that contains 1024 bytes. 我有一个包含1024个字节的ByteBuffer
。
I need to overwrite a short within the buffer at a certain offset at key times. 我需要在关键时刻以某个偏移量覆盖缓冲区内的短路。
I know the ByteBuffer class has putShort()
, but this doesn't overwrite the data, it simply adds it in, which is causing buffer overflows. 我知道ByteBuffer类具有putShort()
,但这不会覆盖数据,只是将其添加进来,这会导致缓冲区溢出。
I'm guessing that there isn't a direct way of doing this using the ByteBuffer
, can someone possibly suggest a way to do this? 我猜测没有使用ByteBuffer
进行此操作的直接方法,有人可以建议一种执行此操作的方法吗?
Thanks 谢谢
Thanks to everyone that replied, seemed it could be done I was just using the wrong version of putShort(). 感谢所有回答,似乎可以做到,我只是使用了错误版本的putShort()。 I guess that's what happens when you stare at the same piece of code for six hours. 我猜这就是当您盯着同一段代码六个小时时发生的情况。
Thanks again 再次感谢
Cannot reproduce the problem, all seems OK 无法重现问题,一切似乎都OK
ByteBuffer bb = ByteBuffer.allocate(20);
bb.putShort(10, (short)0xffff);
System.out.println(Arrays.toString(bb.array()));
prints 版画
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0]
For your special case, you can modify directly the backing array
using the array() method. 对于特殊情况,您可以使用array()方法直接修改backing array
。
Then just insert your two bytes at the proper indexes: 然后只需在适当的索引处插入两个字节即可:
if(myBuffer.hasArray()) {
byte[] array = myBuffer.array();
array[index] = (byte) (myShort & 0xff);
array[index + 1] = (byte) ((myShort >> 8) & 0xff);
}
int p = b.position();
b.position( ZePlace );
p.putShort( ZeValue );
b.position( p );
http://docs.oracle.com/javase/7/docs/api/java/nio/Buffer.html#position%28%29 http://docs.oracle.com/javase/7/docs/api/java/nio/Buffer.html#position%28%29
我认为您可以调用接受位置索引的putShort()这个版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.