How to handle byte arrays with Java’s ByteBuffer

How to handle byte arrays with Java’s ByteBuffer

I had never used the java.nio.ByteBuffer class, but I had a chance to use it in a telegram, so I’ll summarize.

It converts a Map instance to a string and then to a byte array.

Map<String, Object> params = new HashMap<>();
params.put("key1", "val1");
params.put("key2", "val2");
ObjectMapper objectMapper = new ObjectMapper();
String str = objectMapper.writeValueAsString(vdParams);
System.out.println(str); // {"key1":"val1","key2":"val2"}
byte[] byteArr = objectMapper.writeValueAsString(vdParams).getBytes(); // Convert from String to byte array

Allocate capacity with the ByteBuffer.allocate() method and create an instance

Instantiate by specifying the capacity using the ByteBuffer.allocate() method.

The following creates a buf variable with a 64-byte buffer.

ByteBuffer buf = ByteBuffer.allocate(64);

Use the put() method to write to a variable. The argument is a byte[].

ByteBuffer buf = ByteBuffer.allocate(32);
ByteBuffer putBuf = buf.put("test".getBytes("UTF-8")); // Set the byte array of the character "test"
byte[] byteArr = putBuf.array();
System.out.println(Hex.encodeHexString(byteArr));
System.out.println(byteArr.length);

Returns a hexadecimal string of type String with a byte array set to the argument of the org.apache.commons.codec.binary.Hex.encodeHexString() method.

The output is as follows

7465737400000000000000000000000000000000000000000000000000000000

It will fill in the trailing zeros (0x00). This may be useful for fixed-length handling.

Hex.encodeHexString method

The org.apache.commons.codec.binary.Hex.encodeHexString() method converts a byte array to a hexadecimal string.

Hex.decodeHex method

To convert a string in hexadecimal notation to a byte array, use the org.apache.commons.codec.binary.Hex.decodeHexString() method.

byte[] buf = Hex.decodeHex("1640000000".toCharArray());

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL