首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

整型转为字节数组后地址顺序发生了变化,为什么?该怎么解决

2012-04-20 
整型转为字节数组后地址顺序发生了变化,为什么?Java codeimport java.io.*public class Test2{public sta

整型转为字节数组后地址顺序发生了变化,为什么?

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: 785634120x12在int中应该是高地址,转为字节数组后为什么是低地址了?


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

热点排行