How do I getInt from a ByteBuffer with only 1 remaining byte (Java NIO) -
i new java nio , unsure how things nio-ishly.
assume have read data socket bytebuffer
, consumed bytes one, using methods of bytebuffer
. know next thing 4 bytes integer in binary format, want use getint()
, first byte of int in buffer.
the natural thing me fill buffer more bytes connection , continue. if understand correctly, achieve with
buf.compact(); buf.position(buf.limit()); buf.limit(buf.capacity());
and read more bytes.
since there no method behavior, there flip()
method, wonder if thinking wrong. there better ways this?
this situation naturally occur e.g. if connection delivers stream of length + data messages.
buf.compact(); // wrong: buf.position(buf.limit()); // no need to: buf.limit(buf.capacity());
please not change position. position after compact()
pointing first byte after un-getted part of buffer - want it.
setting limit capacity redundant: compact()
you.
Comments
Post a Comment