博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数值类型与字节数组之间的相互转换
阅读量:7039 次
发布时间:2019-06-28

本文共 1437 字,大约阅读时间需要 4 分钟。

hot3.png

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

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

000829_25Sk_121944.png

转载于:https://my.oschina.net/apdplat/blog/501007

你可能感兴趣的文章
CNIT消息:2014年7月中国移动搜索市场研究报告
查看>>
宏正ATEN发行全球首款Cat 5双滑轨19寸LCD KVM切换器
查看>>
consui(二)集群配置
查看>>
Windows Cluster 常用命令
查看>>
AndroidStudio生成jar、so、aar以及上传远程库jcenter
查看>>
Redis 过期键的设置、获取和删除过期时间
查看>>
我的友情链接
查看>>
word,excel,网页上如何打x的n次方
查看>>
Cacti(系统监控)
查看>>
Ubuntu 12.04 修改/etc/resolv.conf重启后还原成修改前状态解决办法
查看>>
我的友情链接
查看>>
Spring集成Quartz定时任务
查看>>
ListView的几种常见的优化方法(三)
查看>>
简约设计中的规律—色彩(一)
查看>>
JavaSE 学习参考:访问修饰符
查看>>
AsyncTask异步任务请求的流程
查看>>
Linux Shell脚本编程--cut命令
查看>>
利用Python 程序实现Linux 网卡 bonding 实现
查看>>
解决Project facet Java version 6.0 is not supported的方法
查看>>
把WinXP系统升级到Win7的方法
查看>>