JAVA 整数网络字节转换(高低位互换)

package test;

public class number {


    private static final byte[] bswap32(int x) {
        return new byte[]{
                (byte) (((x << 24) & 0xff000000) >> 24),
                (byte) (((x << 8) & 0x00ff0000) >> 16),
                (byte) (((x >> 8) & 0x0000ff00) >> 8),
                (byte) (((x >> 24) & 0x000000ff))
        };
    }

    private static final byte[] bswap64(long x) {
        return new byte[]{
                (byte) (((x << 56) & 0xff00000000000000L) >> 56),
                (byte) (((x << 40) & 0x00ff000000000000L) >> 48),
                (byte) (((x << 24) & 0x0000ff0000000000L) >> 40),
                (byte) (((x << 8) & 0x000000ff00000000L) >> 32),
                (byte) (((x >> 8) & 0x00000000ff000000L) >> 24),
                (byte) (((x >> 24) & 0x0000000000ff0000L) >> 16),
                (byte) (((x >> 40) & 0x000000000000ff00L) >> 8),
                (byte) (((x >> 56) & 0x00000000000000ffL))
        };
    }

    public static int bytesToInt(byte[] data) {
        int x = ((data[0] & 0xff) << 24) |
                ((data[1] & 0xff) << 16) |
                ((data[2] & 0xff) << 8) |
                (data[3] & 0xff);
        return x;
    }

    public static Long bytesToLong(byte[] data) {
        Long x = ((data[0] & 0xffl) << 56) |
                ((data[1] & 0xffl) << 48) |
                ((data[2] & 0xffl) << 40) |
                ((data[3] & 0xffl) << 32) |
                ((data[4] & 0xffl) << 24) |
                ((data[5] & 0xffl) << 16) |
                ((data[6] & 0xffl) << 8) |
                (data[7] & 0xffl);
        return x;
    }

    public static void main(String[] args) {
        int x = 1363226913;
        byte[] data = bswap32(x);
        for (byte item : data)
            System.out.printf("hex:%x\n", item);
        System.out.printf("int转换后:%d\n",bytesToInt(data));
        System.out.printf("int还原:%d\n\n",bytesToInt(bswap32(bytesToInt(bswap32(x)))));

        long y = 108492528822595873L;
        data = bswap64(y);
        for (byte item : data)
            System.out.printf("hex:%x\n", item);
        System.out.printf("long转换后:%d\n",bytesToLong(data));
        System.out.printf("long还原:%d\n\n",bytesToLong(bswap64(bytesToLong(bswap64(y)))));
    }
}

你可能感兴趣的:(JAVA)