~/ learn/ comp-348/ cards/ ByteBuffer in practice
1 of 5

Frame a message with a four-byte big-endian length

Frame a message with a four-byte big-endian length

Answer

byte[] body = "PING 42".getBytes(StandardCharsets.UTF_8); ByteBuffer frame = ByteBuffer.allocate(4 + body.length); frame.putInt(body.length); frame.put(body); frame.flip();

putInt writes four bytes in the buffer default order, which is BIG_ENDIAN and therefore network byte order. The bulk put appends the payload, and flip() sets limit to 11 and position to 0 so the whole frame is ready to drain onto a channel.

Harold 4e ch11 §Creating Buffers; §Bulk Methods; §Data Conversion

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/c1522018-69e3-4cd0-84fd-8dbd48f458e5/flashcard utf-8 LF