Java移位操作符

‘>>’右移,低位舍弃
‘<<’左移,低位补0 相当于*2
‘>>>’,无符号右移

        int a = 15; //1111
        int b = a << 2;
        int c = a >> 2;
        int d = a >>> 2;
        System.out.println("b = " + b + "\n" + "c = " + c + "\n" + "d = " + d);


b = 60
c = 3
d = 3

将long类型转换成byte数组,从高位取值在数组尾部向前插入

  private static byte[] longToBytes(long a) {
        byte[] bytes = new byte[8];
        //尾部取高位
        bytes[7] = (byte) (a & 0xff);
        bytes[6] = (byte) (a >> 8 & 0xff);
        bytes[5] = (byte) (a >> 16 & 0xff);
        bytes[4] = (byte) (a >> 24 & 0xff);
        bytes[3] = (byte) (a >> 32 & 0xff);
        bytes[2] = (byte) (a >> 40 & 0xff);
        bytes[1] = (byte) (a >> 48 & 0xff);
        bytes[0] = (byte) (a >> 56 & 0xff);
        System.out.println(Arrays.toString(bytes));
        return bytes;
    }

        long n = 1001L;
        byte[] n_bytes =  longToBytes(n);

[0, 0, 0, 0, 0, 0, 3, -23]

同样byte数组转long类型从数组头部开始去long的高位:

  private static long bytesToLong(byte[] bytes){
        return ((((long) bytes[0] & 0xff) << 56) | (((long) bytes[1] & 0xff) << 48)
        | (((long) bytes[2] & 0xff) << 40) | (((long) bytes[3] & 0xff) << 32)
        | (((long) bytes[4] & 0xff) << 24) | (((long) bytes[5] & 0xff) << 16)
        |(((long) bytes[6] & 0xff) << 8) | (((long) bytes[7] & 0xff)));
    }

    System.out.println(" n = " + bytesToLong(n_bytes));

 n = 1001

同理int占4个字节,转换方式如下:

private static byte[] intToBytes(int n){
        byte[] bytes = new byte[4];
        //尾部取高位
        bytes[3] = (byte) (n & 0xff);
        bytes[2] = (byte) (n >> 8 & 0xff);
        bytes[1] = (byte) (n >> 16 & 0xff);
        bytes[0] = (byte) (n >> 24 & 0xff);
        System.out.println(Arrays.toString(bytes));
        return bytes;
    }

 private static long bytesToInt(byte[] bytes){
        return ((((long) bytes[0] & 0xff) << 24) | (((long) bytes[1] & 0xff) << 16)
                | (((long) bytes[2] & 0xff) << 8) | (((long) bytes[3] & 0xff)));
    }

你可能感兴趣的:(Java移位操作符)