Arithmetic in compiling

simple calc

1
2
3
int calc(int i, int j) {
return ((i + j - 1) & ~(j - 1));
}
  • variable 0 is this -> aload_0

javap -c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int calc(int, int);
Code:
0: iload_1
1: iload_2
2: iadd
3: iconst_1
4: isub
5: iload_2
6: iconst_1
7: isub
8: iconst_m1
9: ixor
10: iand
11: ireturn
a b
[0] push i value into stack
[1] push j value into stack
[2] add; result push stack
[3] push constant 1 into stack
[4] subtract; push result
[5] j value push stack
[6] push constant 1 again
[7] subtract; push result
[8] push constant -1
[9] do XOR; push result
[10] do AND; push result
[11] return int
  • ~(j-1) transform into -1^(j-1)
    exclusive or, -1 bytes is all high bit.
    any int oxr with all high bit, the high bit will be low, low will be high.