java 改大小端

使用bytebuffer的order来实现。

参考博客:https://vimsky.com/examples/usage/bytebuffer-order-method-in-java-with-examples.html

import java.net.*;
import java.nio.ByteBuffer;
import java.lang.Long;
import java.nio.ByteOrder;

public class main {
    public static void main(String[] args) throws Exception {
        main m = new main();
        int t=0x12345678;
        ByteBuffer byteBuffer = m.IntToBigEndByteBuffer(t);
        for(int i=0;i!=4;i++)
        {
            System.out.println(byteBuffer.array()[i]);
        }
        byteBuffer = m.IntToSmallEndByteBuffer(t);
        for(int i=0;i!=4;i++)
        {
            System.out.println(byteBuffer.array()[i]);
        }
    }

    public ByteBuffer IntToBigEndByteBuffer(int t)
    {
        ByteBuffer byteBuffer = ByteBuffer.allocate(4);
        byteBuffer.putInt(t);
        return byteBuffer;
    }

    public ByteBuffer IntToSmallEndByteBuffer(int t)
    {
        ByteBuffer byteBuffer = ByteBuffer.allocate(4);
        byteBuffer.order(ByteOrder.nativeOrder());
        byteBuffer.putInt(t);
        return byteBuffer;
    }
}

文章目录