移位操作符操作运算对象是 位(bit)
它处理的数据类型只能是 整数类型(int)
先大概看一下图,了解它是怎么移动的,下面会解释规则
移位的时候关注两点, 1.移动的方向 2.空缺位置的填补形式.
"有符号"左移位操作符(<<) 将二进制数据左移(在低位补0).
int i = 12448; System.out.println(Integer.toBinaryString(i<<5));
/* 将i的二进制表示 11000010100000
* 向左移动5位,在低位补0,结果是1100001010000000000
*/
int i = -12448; System.out.println(Integer.toBinaryString(i<<5));
/* 将i的二进制表示 11111111111111111100111101100000
*向左移动5位,在低位补0,结果是11111111111110011110110000000000
*/
"有符号"右移位操作符(>>) 将二进制数据右移.(若符号原来是正,就在高位插入0,为负就在高位插入1)
int i = 12448; System.out.println(Integer.toBinaryString(i>>5));
/*二进制表示:11000010100000
*右移5位: 110000101 对比看出,当为正数时高位的0不显示
*/
i = -12448; System.out.println(Integer.toBinaryString(i>>5));
/*二进制表示:11111111111111111100111101100000
*右移5位: 11111111111111111111111001111011
*/
相对有符号右移
"无符号"右移操作符(>>>) 就是说,无论数据是正负都在高位插入0.
i = 12448;System.out.println(Integer.toBinaryString(i>>>5)); /*二进制表示: 11000010100000 *无符号右移5位 110000101
*/
i = -12448;
System.out.println(Integer.toBinaryString(i>>>5));
/*二进制表示: 11111111111111111100111101100000*无符号右移5位 111111111111111111001111011
*/
"移位" 与 "等号" 组合使用 表示方法"<<=或>>=或>>>="
这样会执行两步操作,先移位,然后赋值.
话不多说练习代码贴出来
public class BitManipulation {/*** 位的操作*/public static void main(String[] args) {Random rand = new Random(47);int i = rand.nextInt();int j = rand.nextInt();printBinaryInt("-1", -1);printBinaryInt("+1", +1);int maxpos = 2147483647;printBinaryInt("maxpos", maxpos);int maxneg = -2147483648;printBinaryInt("maxneg", maxneg);printBinaryInt("i", i);printBinaryInt("~i", ~i);printBinaryInt("-i",-i);printBinaryInt("i", i);printBinaryInt("j", j);printBinaryInt("i&j", i&j);printBinaryInt("i|j", i|j);printBinaryInt("i^j", i^j);printBinaryInt("i<<5", i<<5);printBinaryInt("i>>5", i>>5);printBinaryInt("(~i)i>>5", (~i)>>5);printBinaryInt("i>>>5", i>>>5);printBinaryInt("(~i)>>>5", (~i)>>>5);//-----------------------------------------long l = rand.nextLong();long m = rand.nextLong();printBinaryLong("-1l", -1l);printBinaryLong("+1l", +1l);long ll = 9223372036854775807L;printBinaryLong("maxpos", ll);long lln = -9223372036854775808L;printBinaryLong("maxneg", lln);printBinaryLong("l", l);printBinaryLong("~l", ~l);//注意这里的数字 printBinaryLong("m", m);printBinaryLong("l|m", l|m);printBinaryLong("l^m", l^m);printBinaryLong("l<<5", l<<5);printBinaryLong("l>>5", l>>m);printBinaryLong("(~l)>>5", (~1)>>5);printBinaryLong("l>>>5", l>>>5);printBinaryLong("(~l)>>>5", (~l)>>>5);}//对整数进行处理static void printBinaryInt(String s,int i){System.out.println(s+", int:"+ i +",binary:\n"+Integer.toBinaryString(i));}//对长整形数据进行处理static void printBinaryLong(String s,long l){System.out.println(s+",long:"+l+",binary:\n"+Long.toBinaryString(l));}}