From a bytes array:
You can create Bytes objects by wrapping a native byte array:
Bytes bytes = Bytes.wrap(new byte[] {1, 2, 3, 4});Note the underlying array is not copied - any change to the byte array will change the Bytes object’s behavior.
You can also wrap with an offset and a size to select a portion of the array:
// wrapping with an offset of 2 and a size of one byte
Bytes bytes = Bytes.wrap(new byte[] {1, 2, 3, 4}, 2, 1);From a hex string:
You can create Bytes objects from a hexadecimal-encoded string with the fromHexString method:
Bytes bytes = Bytes.fromHexString("0xdeadbeef");The "0x" prefix is optional.
However, this requires an even-sized string. For example, this succeeds:
Bytes bytes = Bytes.fromHexString("01FF2A");This fails:
Bytes bytes = Bytes.fromHexString("1FF2A");You can circumvent this with the fromHexStringLenient method:
Bytes bytes = Bytes.fromHexStringLenient("1FF2A");From a base64-encoded string:
You can create Bytes objects from a base64-encoded string with the fromBase64String method:
Bytes value = Bytes.fromBase64String("deadbeefISDAbest");From primitive types
We also have convenience methods to create Bytes objects from primitive types.
Bytes.of() takes a variadic argument of bytes:
Bytes value = Bytes.of(0x00, 0x01, 0xff, 0x2a);Bytes value = Bytes.ofUnsignedInt(42);More wrapping
Use Bytes.wrapByteBuf(buffer) to wrap a Netty ByteBuf object as a Bytes object.
ByteBuf buffer = Unpooled.buffer(42);
Bytes.wrapByteBuf(buffer);You can apply an offset and size parameter:
Bytes value = Bytes.wrapByteBuf(buffer, 1, 1);Use Bytes.wrapByteBuffer(buffer) to wrap a ByteBuffer object as a Bytes object.
Bytes.wrapByteBuffer(buffer);You can apply an offset and size parameter:
Bytes value = Bytes.wrapByteBuffer(buffer, 1, 1);Use Bytes.wrapBuffer(buffer) to wrap a Vert.x Buffer object as a Bytes object.
Bytes.wrapBuffer(buffer);You can apply an offset and size parameter:
Bytes value = Bytes.wrapBuffer(buffer, 1, 1);Random
You can create random bytes objects of a given length with the Bytes.random() method:
// create a Bytes object of 20 bytes:
Bytes.random(20);Create a Bytes object with our own Random implementation:
Random random = new SecureRandom();
...
Bytes.random(20, random);