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[]toBytes(long l)
to Bytes
ByteBuffer bb = ByteBuffer.allocate(Long.BYTES);
bb.putLong(l);
return bb.array();
byte[]toBytes(Number value)
Converts primitive arithmetic types to byte array.
if (value instanceof Short) {
    return toBytes((Short) value);
} else if (value instanceof Integer) {
    return toBytes((Integer) value);
} else if (value instanceof Long) {
    return toBytes((Long) value);
} else if (value instanceof Float) {
    return toBytes((Float) value);
...
byte[]toBytes(Object obj)
Serializes an Object to byte[].
ByteArrayOutputStream bstream = new ByteArrayOutputStream();
ObjectOutputStream ostream = new ObjectOutputStream(bstream);
ostream.writeObject(obj);
return bstream.toByteArray();
byte[]toBytes(String str, boolean wideChar)
to Bytes
int len = str.length() + 1;
if (wideChar)
    len <<= 1;
byte[] buf = new byte[len];
ByteBuffer bb = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN);
for (int i = 0; i < str.length(); i++) {
    if (wideChar)
        bb.putChar(str.charAt(i));
...
byte[]toBytes(String value)
to Bytes
int offset = 0;
int length = value.length();
ByteBuffer buffer = ByteBuffer.allocate(length * 2);
for (int i = 0; i < length; ++i) {
    buffer.putChar(offset, value.charAt(i));
    offset += 2;
return buffer.array();
...
byte[]toBytes(UUID id)
to Bytes
byte[] bytes = new byte[16];
ByteBuffer bb = ByteBuffer.wrap(bytes);
bb.putLong(id.getMostSignificantBits());
bb.putLong(id.getLeastSignificantBits());
return bytes;
StringtoBytesAsString(UUID uuid)
to Bytes As String
return bytesToString(toByteArray(uuid));
char[]toChars(byte[] bytes)
to Chars
Charset charset = Charset.forName(defaultCharset);
return charset.decode(ByteBuffer.wrap(bytes)).array();
char[]toChars(byte[] bytes)
to Chars
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(byteBuffer);
char[] chars = Arrays.copyOfRange(charBuffer.array(), charBuffer.position(), charBuffer.limit());
Arrays.fill(byteBuffer.array(), (byte) 0);
Arrays.fill(charBuffer.array(), '\u0000');
return chars;
char[]toChars(byte[] bytes)
to Chars
ByteBuffer bf = ByteBuffer.wrap(bytes);
CharBuffer cf = CHARSET.decode(bf);
return cf.array();