数值类型与字节数组之间的相互转换

阅读更多

我们在上文 如何选择使用字符串还是数字呢? 中阐述了使用数值类型的好处,那么问题来了,如何在数值类型与字节数组之间相互转换呢?

我们先看看单个数值类型和字节数组之间的转换,我们以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(Collection 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 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种数值类型,对于我们在数值类型和字节数组之间的转换提供了完备的支持,如下图所示:

数值类型与字节数组之间的相互转换_第1张图片

 

 

 

 

 

 

你可能感兴趣的:(ByteBuffer,java,字节数字,数值类型)