JVM采用大端方式存多字节的数据,判断方法如下:
public static void bytesToInt() throws IOException {
/**
* 将字节数组(byte[])转为整形(int)
*/
byte[] byteAr = new byte[] { 0x78, 0x56, 0x34, 0x12 };
ByteArrayInputStream bais = new ByteArrayInputStream(byteAr);
DataInputStream dis = new DataInputStream(bais);
System.out.println(Integer.toHexString(dis.readInt()));// output: 78563412,说明是大端
} public static void intToBytes() throws IOException {
/**
* 将整形(int)转为字节数组(byte[])
*/
int a = 0x12345678;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(a);
byte[] b = baos.toByteArray();
for (int i = 0; i < 4; i++) {
System.out.print(Integer.toHexString(b[i]));
}
System.out.println();// Output: 12345678,说明是大端
}
采用大小模式对数据进行存放的主要区别在于在存放的字节顺序,大端方式将高位存放在低地址,小端方式将高位存放在高地址。采用大端方式数据存放与阅读顺序一致,符合人类的正常思维,而采用小端方式进行数据存放利于计算机处理。到目前为止,采用大端或者小端进行数据存放,其孰优孰劣也没有定论。
参考资料:
Java's Virtual Machine's Endianness-*
The Java Virtual Machine Specification, Java SE 7 Edition, Chapter 4: The class File Format
A
class
file consists of a stream of 8-bit bytes. All 16-bit, 32-bit, and 64-bit quantities are constructed by reading in two, four, and eight consecutive 8-bit bytes, respectively. Multibyte data items are always stored in big-endian order, where the high bytes come first. In the Java SE platform, this format is supported by interfacesjava.io.DataInput
andjava.io.DataOutput
and classes such asjava.io.DataInputStream
andjava.io.DataOutputStream
.