您的位置:首页 > 编程语言 > Java开发

java中的移位操作

2017-06-30 19:09 232 查看
java中的移位操作仅仅对int和long有效,byte、short、char升级为int后再进行移位

移位操作符有>>(右移)、<<(左移)、>>>(右移)三种,注意两点:1.没有<<<符号 2.移位是不循环的

三种的差别是

>>是带符号右移。负数高位补1,正数补0 ----->>>也就是在高位用符号位进行填充。

<<左移无论负数还是正数,在低位永远补0

>>>是不带符号右移,不论负数还是正数,高位补0( 无符号右移。忽略符号位。空位都以0补齐)

在详细的运算中所有转化为补码逻辑进行移位或者按位运算。

測试程序:

[java] view plain copypublic class Shift {
public static void main(String[] args) {
System.out.println("******************正数左移在低位补0*******************");
int a = 1;
a = a << 2;
System.out.println(a);
System.out.println(Integer.toBinaryString(a));
System.out.println("******************正数右移在高位补0********************");
a = 1;
a = a >> 2;
System.out.println(a);
System.out.println(Integer.toBinaryString(a));
System.out.println("******从上面结果能够看出:移位是不循环的*****");
System.out.println("看看负数的移位:");

System.out.println("***********负数的右移操作高位补1**************");
int i = -1;
System.out.println(i + ":");
System.out.println(Integer.toBinaryString(i));
i = i >> 2;
System.out.println(i);
System.out.println(Integer.toBinaryString(i));
System.out.println("**********负数的左移操作低位补0*****************");
i = i << 2;
System.out.println(i);
System.out.println(Integer.toBinaryString(i));
System.out.println("*************再看看>>>操作符*************");
System.out.println("*************负数的>>>操作高位补0***************");
i = -1;
System.out.println(Integer.toBinaryString(i));
i = i >>> 10;
System.out.println(i + ":");
System.out.println(Integer.toBinaryString(i));
System.out.println("*************注意:没有<<<符号**************");

System.out.println("**********byte类型移位时要强转换*************");
byte k = 10;
System.out.println(Integer.toBinaryString(k));
k = (byte) ((byte) k >>> 2);
System.out.println(Integer.toBinaryString(k));
}
}

执行结果:

******************正数左移在低位补0*******************
4
100
******************正数右移在高位补0********************
0
0
******从上面结果能够看出:移位是不循环的*****
看看负数的移位:
***********负数的右移操作高位补1**************
-1:
11111111111111111111111111111111
-1
11111111111111111111111111111111
**********负数的左移操作低位补0*****************
-4
11111111111111111111111111111100
*************再看看>>>操作符*************
*************负数的>>>操作高位补0***************
11111111111111111111111111111111
4194303:
1111111111111111111111
*************注意:没有<<<符号**************
**********byte类型移位时要强转换*************
1010
10

v=d754dcc0.png) !important; background-position: 0px 0px !important; background-repeat: no-repeat;">v=ba7acbd3.png); background-position: 0px -52px !important; background-repeat: no-repeat;">v=ba7acbd3.png); background-position: 0px -208px !important; background-repeat: no-repeat;">
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: