码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-09-04 02:21:51      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

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

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

技术分享

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

标签:

原文地址:http://my.oschina.net/apdplat/blog/501007

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!