黑马程序员_毕向东_Java基础视频教程——位运算练习(随笔)
位运算(练习)
-
最有效率的方式算出 2乘以 8等于几
2 << 3 = 2 * 2^3 = 2 * 8 = 16
-
对于两个整数变量的值进行互换(不需要第三方变量)
class Test { public static void main(String[] args) { int n = 3, m = 4; System.out.println("n = "+n+ ", m = "+m); //1、通过定义第三方变量来实现 int temp; temp = n; n = m; m = temp; System.out.println("n = "+n+ ", m = "+m); //2-1、不借助第三方变量实现 n = n + m; // n = 3 + 4 = 7; m = n - m; // m = 7 - 4 = 3; n = n - m; // n = 7 - 3 = 4; System.out.println("n = "+n+ ", m = "+m); //这种方法有局限性,如果n和m的值比较大,相加容易超出 int范围,造成损失精度 //2-2、不借助三方变量实现 n = n ^ m; //此时 n =(n ^ m) m = n ^ m; // m = (n ^ m) ^ m == n = 3; n = m ^ n; // n = n ^ m == n ^ (n ^ m); System.out.println("n = "+n+ ", m = "+m); //这种方式属于技巧性 /* 或者直接打印: System.out.println("n = "+m+ ", m = "+n); …… */ } }
获取60的最低4位,通过 60 & 15;
class Text { public static void main(String[] args) { int num = 60; int n1 = num & 15; System.out.println((char) (n1 - 10 + \'A\')); //要获取下一组四位,将 60 右移 4 位 int temp = 60 >> 4; //对temp的值进行最低4位的获取 int n2 = temp & 15; System.out.println( n2 ); /* 0 — 9 \'A\' \'B\' \'C\' \'D\' \'E\' \'F\' 65 66 67 10 11 12 13 14 15 12 - 10 = 2 + \'A\' = (char)67; */ } }
版权声明:本文为chchchch原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。