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)));
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • https://zhuanlan.zhihu.com/p/30108890 移位操作符格式:value << 4v...
    BenjaminCool阅读 999评论 1 0
  • 左移位操作符 << 按照操作符右侧指定的位数将操作符左边的操作数向左移动,低位补0 为什么转二进制后会是32个1...
    心扬阅读 773评论 0 1
  • .1基础语言要素 1)标识符:给类、方法、变量起的名字 A.必须以字母或下划线或$符号开始,其余字符可以是字...
    晨星资源阅读 518评论 0 0
  • 最近工作中被运算效率问题所困扰,比如大数据排序或者去重,因此现在需要补习一下位移运算。 首先讲一下位移概念? 左位...
    等一夏_81f7阅读 1,236评论 0 0
  • 苗语咛喃,水划船痕,梦场江南,雨声慢慢,岸旁垂柳边谁叹梦中人,石桥踏新泥又有几人知,忘忘忘寻寻寻,漓还断江两岸。
    墨乀Anne阅读 126评论 0 0