How is the modulo operator implemented in the HotSpot JVM?

后端 未结 3 1510
醉话见心
醉话见心 2021-01-22 21:21

I understand that the modulus operation can be optimised using a little & wise magic where the divisor is a power of 2...

  • and presuma
3条回答
  •  独厮守ぢ
    2021-01-22 22:08

    Here is one sample code snippet

    public class Test {
    
        public static void main(String[] args)  {
            int a=103;
            int b=5;
            int c=a%b;
            }
        }
    

    Now if you see the compiled code of it You will see

    public static void main(java.lang.String[]);
       flags: ACC_PUBLIC, ACC_STATIC
       Code:
         stack=2, locals=4, args_size=1
            0: bipush        103
            2: istore_1
            3: iconst_5
            4: istore_2
            5: iload_1
            6: iload_2
            7: irem
            8: istore_3
            9: return
    

    bipush- push a byte onto the stack as an integer value ie 103

    istore_1-Pops an int off the stack and stores it in local variable,in the current frame.

    and in 3: iconst_5 constant integer is pushed onto the stack

    istore_2 does the same as istore_1 just variable named changed.

    Then 5: iload_1 and 6:iload_2 both the variables are again pushed onto stack for operations

    now at 7:irem the remainder operator works which you are calling as modulo.
    

    Now how does Remainder operators works. It's Pops two ints(value of a and b) off the operand stack, divides a by b , computes the remainder and pushes the int remainder back onto the stack. The remainder is (b - ((a / b) * b)). This is what is used by the % operator in Java.

提交回复
热议问题