JAVA面试中,面试官最爱问的问题。

Java中怎样将bytes转换为long类型?

在Java中,将字节(byte)数组转换为long类型,你可以使用java.nio.ByteBuffer或者java.io.DataInputStream。下面是两种方法的示例:

使用java.nio.ByteBuffer

 

java复制代码

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class BytesToLongExample {
public static void main(String[] args) {
byte[] bytes = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x7F}; // 示例字节数组
ByteBuffer buffer = ByteBuffer.wrap(bytes);
buffer.order(ByteOrder.BIG_ENDIAN); // 设置字节顺序,根据需要选择BIG_ENDIAN或LITTLE_ENDIAN
long value = buffer.getLong();
System.out.println("Converted long value: " + value);
}
}

使用java.io.DataInputStream

 
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class BytesToLongExample {
public static void main(String[] args) throws IOException {
byte[] bytes = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x7F}; // 示例字节数组
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream dis = new DataInputStream(bais);
long value = dis.readLong();
System.out.println("Converted long value: " + value);
dis.close();
}
}

请注意,字节数组的长度应该至少是8字节(64位),因为long类型是64位的。同时,字节的顺序(大端或小端)可能会影响转换的结果,所以请根据你的数据格式选择合适的字节顺序。在ByteBuffer示例中,你可以通过buffer.order(ByteOrder.BIG_ENDIAN)buffer.order(ByteOrder.LITTLE_ENDIAN)来设置字节顺序。在DataInputStream中,默认使用大端字节顺序。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值