我们在上文 中阐述了使用数值类型的好处,那么问题来了,如何在数值类型与字节数组之间相互转换呢?
我们先看看单个数值类型和字节数组之间的转换,我们以Integer类型为例:
public static byte[] intToBytes(int x) { ByteBuffer intBuffer = ByteBuffer.allocate(Integer.BYTES); intBuffer.putInt(0, x); return intBuffer.array();}public static int bytesToInt(byte[] bytes) { return bytesToInt(bytes, 0, bytes.length);}public static int bytesToInt(byte[] bytes, int offset, int length) { ByteBuffer intBuffer = ByteBuffer.allocate(Integer.BYTES); intBuffer.put(bytes, offset, length); intBuffer.flip(); return intBuffer.getInt();}
接着我们看看多个数值类型和字节数组之间的转换,我们以Long集合和字节数组之间转换为例:
public static byte[] longSetToBytes(Collectionids){ int len = ids.size()*Long.BYTES; ByteBuffer byteBuffer = ByteBuffer.allocate(len); int start = 0; for(Long id : ids){ byteBuffer.putLong(start, id); start += Long.BYTES; } return byteBuffer.array();}public static Set bytesToLongSet(byte[] bytes){ return bytesToLongSet(bytes, 0, bytes.length);}public static Set bytesToLongSet(byte[] bytes, int offset, int length){ Set ids = new HashSet<>(); ByteBuffer byteBuffer = ByteBuffer.allocate(length); byteBuffer.put(bytes, offset, length); byteBuffer.flip(); int count = length/Long.BYTES; for(int i=0; i
由于ByteBuffer支持5种数值类型,对于我们在数值类型和字节数组之间的转换提供了完备的支持,如下图所示: