Java Utililty Methods ByteBuffer from Byte Array

List of utility methods to do ByteBuffer from Byte Array

Description

The list of methods to do ByteBuffer from Byte Array are organized into topic(s).

Method

ByteBufferasByteBuffer(byte... arguments)
as Byte Buffer
return ByteBuffer.wrap(arguments);
byte[]buffer2Bytes(ByteBuffer bbuf)
buffer Bytes
byte[] b = new byte[bbuf.remaining()];
int pos = bbuf.position();
bbuf.get(b);
bbuf.position(pos); 
return b;
byte[]bufToArray(ByteBuffer b)
buf To Array
if (b == null) {
    return null;
} else if (b.hasArray()) {
    if (b.position() == 0 && b.arrayOffset() == 0 && b.limit() == b.capacity()) {
        return b.array();
    } else {
        return Arrays.copyOfRange(b.array(), b.arrayOffset(), b.arrayOffset() + b.remaining());
} else {
    byte[] a = new byte[b.remaining()];
    if (b.remaining() > 0) {
        int bp = b.position();
        b.get(a);
        b.position(bp);
    return a;
byte[]bufToArray(ByteBuffer b)
Converts ByteBuffer to an array - if the buffer is backed by the array but doesn't fully overlap it it performs an array copy.
if (b.hasArray()) {
    if (b.position() == 0 && b.arrayOffset() == 0 && b.limit() == b.capacity()) {
        return b.array();
    } else {
        return Arrays.copyOfRange(b.array(), b.arrayOffset(), b.arrayOffset() + b.remaining());
} else {
    byte[] a = new byte[b.remaining()];
...
ByteBufferbyteBuffer(byte[] a)
Converts an byte array into a direct ByteBuffer.
ByteBuffer buf = directByteBuffer(a.length);
buf.put(a);
buf.rewind();
return buf;
byte[]readByteArray(ByteBuffer byteBuffer, int length)
read Byte Array
byte[] ret = new byte[length];
byteBuffer.get(ret, 0, length);
return ret;
byte[]readByteArray(ByteBuffer in)
read Byte Array
int len = readVInt(in);
if (len < 0)
    return null;
byte[] array = new byte[len];
in.get(array);
return array;
byte[]readByteArray(ByteBuffer logBuf)
Read a byte array from the log.
int size = readInt(logBuf); 
if (DEBUG) {
    System.out.println("pos = " + logBuf.position() + " byteArray is " + size + " on read");
if (size == 0) {
    return ZERO_LENGTH_BYTE_ARRAY;
byte[] b = new byte[size];
...
intreadByteAsInt(ByteBuffer buffer)
read Byte As Int
return Byte.toUnsignedInt(buffer.get());
ByteBufferreadBytes(ByteBuffer bb, int length)
Read length bytes from bb into a new ByteBuffer.
ByteBuffer copy = bb.duplicate();
copy.limit(copy.position() + length);
bb.position(bb.position() + length);
return copy;