Java Utililty Methods Convert via ByteBuffer

List of utility methods to do Convert via ByteBuffer

Description

The list of methods to do Convert via ByteBuffer are organized into topic(s).

Method

byte[]toByteArray(char[] chars)
Converts a char array into a byte array using the default character set.
return toByteArray(chars, java.nio.charset.Charset.defaultCharset().name());
byte[]toByteArray(double value)
to Byte Array
byte[] bytes = new byte[8];
ByteBuffer.wrap(bytes).putDouble(value);
return bytes;
byte[]toByteArray(double[] doubleArray)
to Byte Array
int times = Double.SIZE / Byte.SIZE;
byte[] bytes = new byte[doubleArray.length * times];
for (int i = 0; i < doubleArray.length; i++) {
    ByteBuffer.wrap(bytes, i * times, times).putDouble(doubleArray[i]);
return bytes;
byte[]toByteArray(float[] floatArray)
to Byte Array
int times = Float.SIZE / Byte.SIZE;
byte[] bytes = new byte[floatArray.length * times];
for (int i = 0; i < floatArray.length; i++) {
    ByteBuffer.wrap(bytes, i * times, times).putFloat(floatArray[i]);
return bytes;
byte[]toByteArray(InputStream input, boolean nioCopy)
to Byte Array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (nioCopy)
    nioCopy(input, baos);
else
    copy(input, baos);
return baos.toByteArray();
byte[]toByteArray(int i)
to Byte Array
final ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putInt(i);
return bb.array();
byte[]toByteArray(int integer)
to Byte Array
if (integer <= Short.MAX_VALUE) {
    return toByteArray((short) integer);
return ByteBuffer.allocate(4).putInt(integer).array();
byte[]toByteArray(int value)
Create a fixed-size 32-bit (4 byte) byte[] from an int value using a big endian byte order.
return toByteArray(value, ByteOrder.BIG_ENDIAN);
byte[]toByteArray(int value)
Returns a big-endian representation of value in a 4-element byte array; equivalent to ByteBuffer.allocate(4).putInt(value).array() .
return new byte[] { (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value };
byte[]toByteArray(int[] data, boolean bigEndian)
to Byte Array
ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4);
if (bigEndian) {
    byteBuffer.order(ByteOrder.BIG_ENDIAN);
} else {
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(data);
...