java的大小端和转换

一直以为大小端针对的bit的顺序,今天才知道:大小端的分度值是 byte,即每一个byte都是按照正常顺序,但是byte组装成一个int 或者是 long等时每个byte的摆放位置不同。

测试代码:

public class BufferTest {
    @Test
    public static void main(String[] args) {
        ByteBuffer buffer= ByteBuffer.allocate(4);
        buffer.order(ByteOrder.BIG_ENDIAN);
        buffer.asIntBuffer().put(1);
        System.out.println(buffer.array()[3]);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        System.out.println(buffer.array()[3]);
    }
}

 

也可以自己转换:

public class BufferTest {
    @Test
    public static void main(String[] args) {
        ByteBuffer buffer= ByteBuffer.allocate(4);
        buffer.order(ByteOrder.BIG_ENDIAN);
        buffer.asIntBuffer().put(1);
        System.out.println(buffer.array()[3]);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        System.out.println(buffer.array()[3]);
    }
}

 

posted @ 2015-01-18 00:16  高兴的博客  阅读(15595)  评论(1编辑  收藏  举报