![0ded053392277a526e3320b2a3ea6e44.png](https://i-blog.csdnimg.cn/blog_migrate/2e29831cada56525af0f46790ad954d4.jpeg)
4.位运算:
(0).与运算:
//规则:两数同为1,结果才为1.
n = 0 & 0; //0
n = 0 & 1; //0
n = 1 & 0; //0
n = 1 & 1; //1
(1).或运算:
//规则:任意为1则为1.
n = 0 | 0; //0
n = 0 | 1; //1
n = 1 | 0; //1
n = 1 | 1; //1
(2).非运算:
//规则:取反
n = ~1; //0
n = ~0; //1
(3).异或运算:
//规则:不同为1,相同为0.
n = 0 ^ 0; //0
n = 0 ^ 1; //1
n = 1 ^ 0; //1
n = 1 ^ 1; //0
(4).对于两个整数进行位运算,就是要按位对齐。
public class Main{
public static void main(String[] args){
int i = 167776589; //00001010 00000000 00010001 01001101
int n = 167776512; //00001010 00000000 00010001 00000000
System.out.println(i & n); //167776512
}
}
5.类型自动提升与强制转换:
(0).若运算过程中,参与运算的两个数的类型不同,结果为较大类型的整型。
//short 与 int 运算,结果总是 int , short 被自动转型为 int 。
public class Main{
public static void main(String[] args){
short s = 1234;
int i = 123456;
int x = s + i; //s被自动转型为int
short x = s + i; //编译错误
}
}
(1).强制转换:
//将大范围的整数转换为小范围的整数。
int i = 12345;
short s = (short) i;
//注意:超出范围的强制转型会得到错误的结果,因为转型时,
//int 的两个高位字节直接被扔掉,仅保留了低位的两个字节。
public class Main{
public static void main(String[] args){
int i1 = 1234567;
short s1 = (short) i1; //-10617
int i2 = 12345678;
short s2 = (short) i2; //24910
}
}