咱们在上文 如何选择使用字符串仍是数字呢? 中阐述了使用数值类型的好处,那么问题来了,如何在数值类型与字节数组之间相互转换呢?java
咱们先看看单个数值类型和字节数组之间的转换,咱们以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集合和字节数组之间转换为例:.net
public static byte[] longSetToBytes(Collection<Long> ids){ 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<Long> bytesToLongSet(byte[] bytes){ return bytesToLongSet(bytes, 0, bytes.length); } public static Set<Long> bytesToLongSet(byte[] bytes, int offset, int length){ Set<Long> 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<count; i++) { ids.add(byteBuffer.getLong()); } return ids; }
因为ByteBuffer支持5种数值类型,对于咱们在数值类型和字节数组之间的转换提供了完备的支持,以下图所示:code