&和&&的区别
2013-11-06
&& 逻辑运算符
&&和||是用于条件判断,而&和|是位运算。
· 【&】
//相当于二进制减法;
//计算原理:数值转成二进制 > 二进制相减(遇0为0) > 再将二进制计算结果转成数值;
(1&1) = (0001 - 0001 = 0001) = 1
(1&2) = (0001 - 0010 = 0000) = 0
(2&2) = (0010 - 0010 = 0010) = 2
(7&5) = (0111 - 0101 = 0101) = 5
(7&8) = (0111 - 1000 = 0000) = 0
(8&4) = (1000 - 0100 = 0000) = 0
//如:true = 0001, false = 0000
(true|false) = (0001 - 0000 = 0000) = false
(true|true) = (0001 - 0001 = 0001) = true
(false|false) = (0000 - 0000 = 0000) = false
· 【|】
//相当于二进制加法;
//计算原理:数值转成二进制 > 二进制相减(遇1为1) > 再将二进制计算结果转成数值;
(1|1) = (0001 + 0001 = 0001) = 1
(1|2) = (0001 + 0010 = 0011) = 3
(2|2) = (0010 + 0010 = 0010) = 2
(7|5) = (0111 + 0101 = 0111) = 7
(7|8) = (0111 + 1000 = 1111) = 15
(8|4) = (1000 + 0100 = 1100) = 12
//如:true = 0001, false = 0000
(true|false) = (0001 + 0000 = 0001) = true
(true|true) = (0001 + 0001 = 0001) = true
(false|false) = (0000 + 0000 = 0000) = false
· 【&&】
//条件与
//其中一方为false则返回false
//左右两方同时为true则返回true
(true&&false) = false
(true&&true ) = true
(false&&false) = false
· 【||】
//条件或
//其中一方为true则返回true
//左右两方同时为false则返回false
(true || false) = true
(true || true ) = true
(false || false) = false