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]);
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM