移位操作是把数据看作是二进制数,然后将其向左或向右移动若干位的运算。在Java编程语言中,移位操作符包含三种,分别是
<<
(左移)、
>>
(带符号右移)和
>>>
(无符号右移),这三种操作符都只能作用于
long
、
int
、
short
、
byte
、
char
这四种基本的整型类型上。
左移操作符 <<
左移操作符
<<
是将数据转换成二进制数后,
向左移若干位,高位丢弃,低位补零
。看如下例子:
publicstaticvoidmain(String[] args) {
int i = -1;
System.out.println("Before << , i's value is " + i);
System.out.println("i's binary string is " + Integer.toBinaryString(i));
i <<= 10;
System.out.println("After << , i's value is " + i);
System.out.println("i's binary string is " + Integer.toBinaryString(i));
Before << , i's value is -1
i's binary stringis11111111111111111111111111111111
After << , i's value is -1024
i's binary stringis11111111111111111111110000000000
Before >> , i1's value is 4992
i1's binary stringis1001110000000
After >> , i1's value is 4
i1's binary stringis100
Before >> , i2's value is -4992
i2's binary stringis11111111111111111110110010000000
After >> , i2's value is -5
i2's binary stringis11111111111111111111111111111011
Before >>> , i3's value is -4992
i3's binary stringis11111111111111111110110010000000
After >>> , i3's value is 4194299
i3's binary stringis1111111111111111111011
真的懂了吗?
对 short、byte、char 的移位操作
再看如下例子:
publicstaticvoidmain(String[] args) {
byte b = -1;
System.out.println("Before >> , b's value is " + b);
System.out.println("b's binary string is " + Integer.toBinaryString(b));
b >>>= 6;
System.out.println("After >> , b's value is " + b);
System.out.println("b's binary string is " + Integer.toBinaryString(b));
Before >> , b's value is -1
b's binary stringis11111111111111111111111111111111
After >> , b's value is -1
b's binary stringis11111111111111111111111111111111
publicstaticvoidmain(String[] args) {
byte b = -1;
System.out.println("Before >> , b's value is " + b);
System.out.println("b's binary string is " + Integer.toBinaryString(b));
System.out.println("After >> , b's value is " + (b >>> 6));
System.out.println("b's binary string is " + Integer.toBinaryString(b >>> 6));
在该例子中,没有使用 >>>= 对 b 进行再赋值,而是直接将 b >>> 6 进行输出(需要注意的是,b >>> 6 的结果为 int 类型),其输出如下:
Before >> , b's value is -1
b's binary stringis11111111111111111111111111111111
After >> , b's value is 67108863
b's binary stringis11111111111111111111111111
Before >>> , i4's value is -1
i4's binary stringis11111111111111111111111111111111
After >>> 31 , i4's value is 1
i4's binary stringis1
After >>> 32 , i4's value is -1
i4's binary stringis11111111111111111111111111111111
After >>> 33 , i4's value is 2147483647
i4's binary stringis1111111111111111111111111111111