java byte to long_java 中怎样将 bytes 转换为 long 类型

这篇博客介绍了三种将Java字节数组转换为long的方法:1) 直接通过位运算;2) 使用java.nio.ByteBuffer;3) 利用java.io.DataInputStream。并提供了详细的代码实现和验证过程。
摘要由CSDN通过智能技术生成

展开全部

方法有以下三种:

1、不借助其他任何已经有的类,直接进行转换。e69da5e6ba9062616964757a686964616f31333365643662

2、借助java.nio.ByteBuffer实现,只要将byte[]转换为ByteBuffer就可以实现所有primitive类型的数据读取。

3、借助java.io.DataInputStream实现,只要将byte[]转换为DataInputStream就可以实现所有primitive类型的数据读取。

具体步骤如下:

1、/**

* 将字节数组转为long

* 如果input为null,或offset指定的剩余数组长度不足8字节则抛出异常

* @param input

* @param offset 起始偏移量

* @param littleEndian 输入数组是否小端模式

* @return

*/

public static long longFrom8Bytes(byte[] input, int offset, boolean littleEndian){        long value=0;        // 循环读取每个字节通过移位运算完成long的8个字节拼装

for(int  count=0;count<8;++count){            int shift=(littleEndian?count:(7-count))<<3;

value |=((long)0xff<< shift) & ((long)input[offset+count] << shift);

}        return value;

}

2、/**

* 利用 {@link java.nio.ByteBuffer}实现byte[]转long

* @param input

* @param offset

* @param littleEndian 输入数组是否小端模式

* @return

*/

public static long bytesToLong(byte[] input, int offset, boolean littleEndian) {

// 将byte[] 封装为 ByteBuffer

ByteBuffer buffer = ByteBuffer.wrap(input,offset,8);        if(littleEndian){            // ByteBuffer.order(ByteOrder) 方法指定字节序,即大小端模式(BIG_ENDIAN/LITTLE_ENDIAN)

// ByteBuffer 默认为大端(BIG_ENDIAN)模式

buffer.order(ByteOrder.LITTLE_ENDIAN);

}        return buffer.getLong();

}

3、public void test() throws IOException {

String input="net.gdface.facelog.dborm.person.FlPersonBeanBase";

byte[] md5 = getMD5(input.getBytes());

System.out.printf("md5 [%s]\n",toHex(md5));

// 三种方式运算结果对比验证

DataInputStream dataInput = new DataInputStream(new ByteArrayInputStream(md5));

long l1 = dataInput.readLong();

long l2 = dataInput.readLong();

System.out.printf("l1=0x%x l2=0x%x,DataInputStream\n", l1,l2);

long ln1 = bytesToLong(md5,0, false);

long ln2 = bytesToLong(md5,8, false);

System.out.printf("ln1=0x%x ln2=0x%x,ByteBuffer\n", ln1,ln2);

long ll1 = longFrom8Bytes(md5,0, false);

long ll2 = longFrom8Bytes(md5,8, false);

System.out.printf("ll1=0x%x ll2=0x%x\n", ll1,ll2);

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值