JVM大端判断

博客介绍了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.

转载于:https://www.cnblogs.com/z-sm/p/6049172.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值