char类型byte类型或short类型进行无符号右移遇到的神奇问题

代码

package com.ggp.test.Third;

/**
 * @Author:ggp
 * @Date:2019/7/27 17 23
 * @Description:
 */
public class URShift {
    public static void main(String[] args) {
        byte b = -1;
        System.out.println(Integer.toBinaryString(b));
        System.out.println(Integer.toBinaryString(b>>>10));
        System.out.println(b>>>10);

        byte c = -1;
        System.out.println(Integer.toBinaryString(c));
        c>>>=10;
        System.out.println(Integer.toBinaryString(c));
        System.out.println(c);
    }
}

运行结果

11111111111111111111111111111111
1111111111111111111111
4194303
11111111111111111111111111111111
11111111111111111111111111111111
-1

Process finished with exit code 0

刚开始我很不理解为什么会有不同的输出,这两种的输入区别在哪里?

通过仔细观察我弄懂了原因。

第一种和第二种相比,第二种其实多了一步转类型。

首先short和byte在java中其实是以32字节的方式存储的,也就是相当于一个int

第一种,b>>>10

首先b会转成int然后右移10位变成

11111111 11111111 11111111 11111111  》》 00000000 00111111 11111111 11111111

因为本身就是int 打印结果就是11111 11111111 11111111

第二种,b>>>10之后还会进行转型

11111111 11111111 11111111 11111111  》》 00000000 00111111 11111111 11111111 》》11111111 11111111

打印的时候在转int  》》11111111 11111111 11111111 11111111 

 

 

你可能感兴趣的:(java基础)