When should I use this kind of int variables?

后端 未结 5 1019
忘了有多久
忘了有多久 2021-01-15 23:48

Some int variables in java.awt.Event class is set by bitwise. Like below:

/**
 * This flag indicates that the Shift key was down when the ev         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-16 00:33

    Because those values aren't increasing by one. They are powers of two and used for testing with bitwise-or, exclusive-or, binary-and, etc.

    int[] arr = { 1 << 0, 1 << 1, 1 << 2, 1 << 3 };
    System.out.println(Arrays.toString(arr));
    

    Output is

    [1, 2, 4, 8]
    

    It's a way of writing 2n where n is the number to the right of the <<.

提交回复
热议问题