java中有三种移位运算符
<<
:左移运算符,num << 1,相当于num乘以2>>
:右移运算符,num >> 1,相当于num除以2>>>
:无符号右移,忽略符号位,空位都以0补齐
正数时:
public class ShiftTest {
@Test
public void shiftTest() {
int num = 84;
System.out.printf("num 二进制:{%s}\r\n", Integer.toBinaryString(num));
System.out.printf("num >>> 2 = {%s} = {%d}\r\n", int2ByteStr(num >>> 2), (num >>> 2));
System.out.printf("num >> 2 = {%s} = {%d}\r\n", int2ByteStr(num >> 2), (num >> 2));
System.out.printf("num << 2 = {%s} = {%d}\r\n", int2ByteStr(num << 2), (num << 2));
}
/**
* @param num
*/
private String int2ByteStr(int num) {
return Integer.toBinaryString(num);
}
}
结果图:
负数时:
@Test
public void shiftTest() {
int num = -84;
System.out.printf("num 二进制:{%s}\r\n", Integer.toBinaryString(num));
System.out.printf("num >>> 2 = {%s} = {%d}\r\n", int2ByteStr(num >>> 2), (num >>> 2));
System.out.printf("num >> 2 = {%s} = {%d}\r\n", int2ByteStr(num >> 2), (num >> 2));
System.out.printf("num << 2 = {%s} = {%d}\r\n", int2ByteStr(num << 2), (num << 2));
}
/**
* @param num
*/
private String int2ByteStr(int num) {
return Integer.toBinaryString(num);
}
结果图: