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
中,默认使用大端字节顺序。