Here you can just do a putShort((short)(buffer.position()-Short.MAX_VALUE)