Solved ProtocolLib check if value contains bitmask

Discussion in 'Spigot Plugin Development' started by SpleshXD, Jun 14, 2021.

Thread Status:
Not open for further replies.
  1. Hey, I'm sure this question is dumb and there is probably a bitwise operator for something like this.

    Currently, this is my code:
    Code (Java):
    WrapperPlayServerEntityMetadata packet = new WrapperPlayServerEntityMetadata(event.getPacket());

    packet.getMetadata().forEach(wrappedWatchableObject -> {
        if (wrappedWatchableObject.getIndex() == 0) {
            // Check if value contains bitmask 0x20
        }
    });

    I know that I can get the value and raw value (Btw, what is the difference between them?) using
    Code (Java):
    wrappedWatchableObject.getValue() // or .getRawValue()
    It returns a byte, how do I check if it "contains" the bitmask?

    Basically what I'm trying to do is to check whether the player is invisible (Bit mask 0x20) or not, if it isn't, run some code.
     
  2. Uhhh, (value & mask) == mask ?
     
  3. 0x20 is in binary 0010 0000, this means that if the returned byte has a 1 at the bite 5, the player is invisible. To check if this is true we want to remove every other bite but the one we want so we use an and operator
    Code (Java):
    byte mask = 0x20;
    byte value = ...;
    if((value & mask) == mask) {
      // the player is invisible
    }
    This operation makes an and on every bite so if the value is 0011 0010 in binary we do this:
    Code (Text):
    0 & 0 = 0
    1 & 0 = 0
    0 & 0 = 0
    0 & 0 = 0
    1 & 0 = 0
    1 & 1 = 1
    0 & 0 = 0
    0 & 0 = 0
    The result is the used mask if the value has every bite that the mask has at 1, so we check if the result is the mask
     
    • Like Like x 1
  4. That worked, thank you!
    If I'm on the topic of the bitmasks, how do I add a mask to an existing byte? Do I just do
    Code (Text):
    value | mask
    ?
     
  5. Yes
     
Thread Status:
Not open for further replies.