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集合和字节数组之间转换为例:

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

ids.add(byteBuffer.getLong());

}

return ids;

}

由于ByteBuffer支持5种数值类型,对于我们在数值类型和字节数组之间的转换提供了完备的支持,如下图所示:

e8f4522a0a7db1e65a7f3f3385f7fca6.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值