最近做的笔试题中出现这样一道题:
题目:What results from the following code fragment?
int i = 5;
int j = 10;
System.out.println(i + ~j);
A Compilation error because”~”doesn’t operate on integers
B -5
C -6
D 15
答案是C。原来~是按位取反
10的原码: 0000 0000 0000 1010
由于在计算机中以补码形式存储,又正数的补码就是原码本身,所以计算机可以直接计算~10
~10按位取反:1111 1111 1111 0101
那还是计算机中以补码形式存储,所以当前的计算后的~10是补码形式,我们要对其求原码,又因为负数的补码是原码按位取反再加1,所以,我们可以得到反码(补码减1)
~10的反码: 1111 1111 1111 0100
~10的原码: 1000 0000 0000 1011
所以~10是-11在计算机的补码,所以最终答案是C。