JVM大端判断

JVM采用大端方式存多字节的数据,判断方法如下:

 1     public static void bytesToInt() throws IOException {
 2         /**
 3          * 将字节数组(byte[])转为整形(int)
 4          */
 5         byte[] byteAr = new byte[] { 0x78, 0x56, 0x34, 0x12 };
 6         ByteArrayInputStream bais = new ByteArrayInputStream(byteAr);
 7         DataInputStream dis = new DataInputStream(bais);
 8         System.out.println(Integer.toHexString(dis.readInt()));// output: 78563412,说明是大端
 9     }
10 
11     public static void intToBytes() throws IOException {
12         /**
13          * 将整形(int)转为字节数组(byte[])
14          */
15         int a = 0x12345678;
16         ByteArrayOutputStream baos = new ByteArrayOutputStream();
17         DataOutputStream dos = new DataOutputStream(baos);
18         dos.writeInt(a);
19         byte[] b = baos.toByteArray();
20         for (int i = 0; i < 4; i++) {
21             System.out.print(Integer.toHexString(b[i]));
22         }
23         System.out.println();// Output: 12345678,说明是大端
24     }

 

采用大小模式对数据进行存放的主要区别在于在存放的字节顺序,大端方式将高位存放在低地址,小端方式将高位存放在高地址。采用大端方式数据存放与阅读顺序一致,符合人类的正常思维,而采用小端方式进行数据存放利于计算机处理。到目前为止,采用大端或者小端进行数据存放,其孰优孰劣也没有定论。

参考资料:

Java's Virtual Machine's Endianness-StackOverFlow

The Java Virtual Machine Specification, Java SE 7 Edition, Chapter 4: The class File Format

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 interfaces java.io.DataInput and java.io.DataOutput and classes such as java.io.DataInputStream and java.io.DataOutputStream.

posted @ 2016-11-09 22:46  March On  阅读(1113)  评论(0编辑  收藏  举报
top last
Welcome user from
(since 2020.6.1)