Reads a 24 bit length field and returns a ByteBuffer corresponding to the array of bytes of this length following the length field. - Java java.nio

Java examples for java.nio:ByteBuffer Read

Description

Reads a 24 bit length field and returns a ByteBuffer corresponding to the array of bytes of this length following the length field.

Demo Code


import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Iterator;
import org.apache.log4j.Logger;

public class Main{
    /**// w ww.  j a  va2  s .  c  o m
     * Reads a 24 bit length field and returns a ByteBuffer corresponding to the
     * array of bytes of this length following the length field.
     * 
     * @param buf
     * @return
     */
    final static public ByteBuffer subBuffer24(ByteBuffer buf) {
        int len = getUnsigned24(buf);
        byte[] array = buf.array();
        int arrayOffset = buf.arrayOffset();
        int position = buf.position();
        buf.position(position + len);
        return ByteBuffer.wrap(array, arrayOffset + position, len);
    }
    /**
     * Return 24 unsigned bits as an integer. Big endian.
     * 
     * @param buf
     * @return
     */
    final public static int getUnsigned24(ByteBuffer buf) {
        int length = (0xff & buf.get());
        length = (length << 8) | (0xff & buf.get());
        length = (length << 8) | (0xff & buf.get());
        return length;
    }
}

Related Tutorials