java中关于移位运算符的demo与总结

时间:2021-06-02 19:31:56

首先,移位运算符有三种,其操作类型只支持:byte / short / char / int和long五种。

<< 左移运算符,表示将左边的操作数的二进制数据向左移动*位,移动后空缺位以0填充,多余位舍弃。(等同于乘2的n次方)

>> 右移运算符,二进制数据向右移动*位,就在其二进制数据后抹掉几位?(这里还不错定,但个人理解是这样的)(等同于除2的n次方)

>>> 无符号右移运算符,不管移动前最高位是0还是1,右移后左侧产生的空位部分都以0来填充。

下面我们借一个demo帮助理解:

public static void main(String[] args){
int a = 16;
int b = a << 2;//左移2,等同于16 * 2的2次方,也就是16 * 4
int c = a >> 2;//右移2,等同于16 / 2的2次方,也就是16 / 4 System.out.println("a的二进制数据为:" + Integer.toBinaryString(a));
System.out.println("a左移后二进制数据为:" + Integer.toBinaryString(b));
System.out.println("a右移后二进制数据为:" + Integer.toBinaryString(c)); System.out.println("a左移后的值为:" + b);
System.out.println("a右移后的值为:" + c);
}
}

查看运行结果,如图所示:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAW4AAACoCAIAAABPBpPFAAAamklEQVR4nO2cbXRURZrH74f5sOfsnvm2e/bDftk9c+bM6PGM72NHNq6bUXHPrjqzq6szSlyOaXAIuCoiOpqgoOCqJOALb83bigYRAQl0EDOAGEDkJW+gYEcSQhAhpBNIIJDEvfuhu2/XvfVU3arble50+P/Oc7SpW/Xcp97+t+p2uqzj31+EwWCwDM3KeQQwGGwUGCEl0dr9MBgMpmUWLyJNx3tgsCvTbNtOzAIbpJpCseksVkdy3pEwWA4tMXlyPX9HHIrKYEFHYLCEQUdEqOgDpAQG62nCkkSKqpREa/c3tvXAYFeyQUfk+KoEISWrIiXbo3O2bX7t041vbFpfuX7tW2vWvPtB1aKVq5ZGVq5YsOy9ZVXVu5o7ct73sEys5t2xWxbczdm/7G9uynlsOTFIiZwgUrJi4aPNPf3nz3d19cQ74/Hvu+InznS3nonHfuhe93nboY74jsaWt1ds2H6gLefdDwts61+7rudsu8f2rPrPTf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iWwRYlagolKeOMsS/0E/+EBu/uwX5jPbRR7bmt6qOOngSRQIhcii5qa6U+MqfulsNouHkLyMty3Kf4ZBsX0gJyGf0jj5KltGXEjKzaIGQiZT45ldclagXVyTRokkJcZ0t5BI1cg0IwMhH++gj3Q2CZznAp/N+hltKVFYlKksVNtFXYmKVBe5f9HOigVUJyGf0jj7SmnW6RbImJb7ByNdZZKLKaoXZKkbD/HsTSAnIZwIefeRyoSMlKqsAcuFA+lFfVqhLia6O6CD/KhgbHJDHBPkyWDTVRXOeLaXo3zdRsiohb2RJvxuSCI1u8ABcmeCQAQCAASAlAAADQEoAAAbA0Uc+t1aLEYArHRx9JMsJKQFAERx9RAfj5FePB4ArGRx95HMXxXgAuMLB0Udet1pCCQBIgKOP9OLJWEpwxBEYneDoI+FCQz1C9dUKjjgCo5UgRx9pLf6ddDaDfPaqOPdd8qhLmK+UqKyAVKQERxyBUYz20UfObCd8Cb5SsbnZKBEIReei6a0iJSoKqOhWHRxxBEY3ekcfyWeURErIPKIFQiZS4ptfcVWiXlwRHHEERjfaRx8liylPP89ygE/niw+3lKisSlSWKmyihsRgVQJGI3pHH6WL6byS1E3M+apEoguQEgBIAh59RD7bFae0bzYV5wHuS6ZLcvr6DACOOAKjFZNfBvuuNRSnYoarEvJGlvS7IYnQ6AYPwJUJDhkAABgAUgIAMACkBABgAEgJAMAAkBIAgAEgJQAAA0BKAAAGgJQAAAwAKQEAGABSAgAwAKQEAGAASAkAwACQEgCAASAlAAADQEoAAAaAlAAADAApAQAYAFICADAApAQAYABICQDAAJASAIABICUAAANASgAABoCUAAAMACkBABgAUgIAMACkBABgAEgJAMAAkBIAgAEgJQAAA0BKAAAGgJQAAAwAKQEAGABSAgAwAKQEAGAAl5Rc0qSvr0+3CABgVOKSkuNu2hU4DgAAx4//P/nKNi5T20fBAAAAAElFTkSuQmCC" alt="" />

首先,16的二进制数据为:10000;

左移两位,10000变成1000000;

右移两位,10000变成100;

把得到的二进制数据转换成普通数据后,

a左移后的值为64,既16 * 2的2次方(16 * 4)。

a右移后的值为4,既16 / 2的2次方(16 / 4)。

看完这个demo再理解移位运算符是不是就简单很多?