Weyu‘s blog

  • 首页
  • 代码
  • 作品
  • 学习
  • 折腾
  • 随笔
  • 关于博主
  • 时光映像
  • 我的网盘
  • 文章归档
  • 友情链接

Day3 笔记 位运算符的基本用法与特点

  • admin
  • 2017-02-12
  • 0

用法1:

class Demo3_Operator {
 public static void main(String[] args) {
  /*
  &,|,^,~ 的用法
  &:有0则0
  |:有1则1
  ^:相同则0,不同则1
  ~:按位取反
  */
  System.out.println(6 & 3);   //2
  System.out.println(6 | 3);   //7
  System.out.println(6 ^ 3);   //5
  System.out.println(~6);    //-7

 }
}
/*
     110
&   011
-----------
     010

     110
|    011
-----------
     111

     110
^   011
------------
     101

     00000000 00000000 00000000 00000110  6的原码反码补码都是本身
     11111111 11111111 11111111 11111001  对6 取反
-    00000000 00000000 00000000 00000001
----------------------------------------------------------------
     11111111 11111111 11111111 11111000  反码
     10000000 00000000 00000000 00000111  原码(-7)

 

 

*/

用法2:

class Demo5_Operator {
 public static void main(String[] args) {
 /*
 <<:左移  左边最高位丢弃 , 右边补齐 0
 >>:右移  最高位是0,左边补齐0;最高位是1,左边补齐1
 >>>:无符号右移 无论最高位是0 还是 1,左边补齐 0
 -面试题:最有效率的算出 2 * 8 的结果.
 */

  //左移,向左移动几位就是乘以2的几次幂
  System.out.println(12 << 1);  //24
  System.out.println(12 << 2);  //48
  /*
  00000000 00000000 00000000 00001100   12的补码
  (0)0000000 00000000 00000000 000011000   24的补码
 (00)000000 00000000 00000000 0000110000   48的补码
  */


  //右移,向右移动几位就是除以2的几次幂
  System.out.println(12 >> 1);    //6
  System.out.println(12 >> 2);    //3

  /*
  00000000 00000000 00000000 00001100   12的补码
  000000000 00000000 00000000 0000110(0)  6
  0000000000 00000000 00000000 000011(00)  3
  */

  //最有效率的算出 2 * 8 的结果
  System.out.println( 2 << 3 );
 }
}

位异或运算符的特点:

class Demo4_Operator {
	public static void main(String[] args) {
		/*
		-位异或运算符的特点

		 ^的特点:一个数据对两一个数据位异或两次,该数本身不变.
		*/
		System.out.println(5 ^ 10 ^ 10);
		System.out.println(5 ^ 10 ^ 5);
		/*
		面试题:请自己实现两个整数变量的交换(不需要定义第三方变量)
		
		*/
		int x = 10;
		int y = 5;

		//需要第三方变量,开发推荐使用这种
		//int temp;
		//temp = x;
		//x = y;
		//y = temp;

		//不需要定义第三方变量,有弊端,有可能会超出int的取值范围
		/*
		x = x + y;				//10 + 5 = 15
		y = x - y;				//15 - 5 = 10
		x = x - y;				//15 - 10 = 5
		*/
		
		//不需要定义第三方变量
		x = x ^ y;					//10 ^ 5
		y = x ^ y;					//10 ^ 5 ^ 5     y = 10
		x = x ^ y;					//10 ^ 5 ^ 10    x = 5


		System.out.println("x = " +  x + ",y= " + y );


	}
}
© 2025 Weyu‘s blog
  • {{ item.name }}
  • {{ item.name }}