日期:2014-05-20  浏览次数:20679 次

整型转为字节数组后地址顺序发生了变化,为什么?
Java code
import java.io.*;

public class Test2
{
    public static void main(String[] args) throws IOException
    {
        int a = 0x12345678;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeInt(a);
        byte[] b = baos.toByteArray();
        for(int i = 3; i >= 0; i--)
        {
            System.out.print(Integer.toHexString(b[i]));
        }
        System.out.println();
    }
}
// Output: 78563412
0x12在int中应该是高地址,转为字节数组后为什么是低地址了?



------解决方案--------------------
啥时候应该是高地址了?Java采取的是big endian方式存储数据。
低地址 高地址
----------------------------------------->
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 | 12 | 34 | 56 | 78 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
你的for循环从后向前打印输出的。
------解决方案--------------------
for(int i = 3; i >= 0; i--)
{
System.out.print(Integer.toHexString(b[i]));
 }