When should I use this kind of int variables?

后端 未结 5 1022
忘了有多久
忘了有多久 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:30

    The example is easy, let's say that the control and shift key are depressed. Using the above, this would make the bitstring something like this:

    ...11
    

    To make it concrete, let's use an 8 bit string, say something like this:

    0111 0011
    

    This would represent that several keys may have been depressed, but perhaps you are only interested in the shift and control keys. If you want to know when both the shift and control key are depressed you can create a new combination:

    CTRL_AND_SHIFT_MASK = SHIFT_MASK | CTR_MASK;
    

    Then you can do a bitwise and to determine whether or not the returned bit string has both the control and shift keys depressed:

    final boolean isCtrlAndShift = (CTRL_AND_SHIFT_MASK & val) == CTRL_AND_SHIFT_MASK;
    

    By doing a bitwise and, if the two bits for CTRL and SHIFT aren't both 1, then and'ing will result in one of the two bits becoming 0. All other bits will be 0 regardless (since they are 0 in CTRL_AND_SHIFT_MASK). So if you and it with your value val then it should give back your CTRL_AND_SHIFT_MASK otherwise only one or neither is depressed.

提交回复
热议问题