caarlos0
caarlos0

Reputation: 20633

Doubts with the Java operators

i was looking some code of some GWT classes, and, shamefully, i was unable to understand this part of code:

private void toggleHover() {
    // Toggle hovering.
    int newFaceID = getCurrentFace().getFaceID() ^ HOVERING_ATTRIBUTE;

    // Remove disabled.
    newFaceID &= ~DISABLED_ATTRIBUTE;
    setCurrentFace(newFaceID);
  }

I do not know very well the java operators, so, my question is:

What exactly happens in:

a) getCurrentFace().getFaceID() ^ HOVERING_ATTRIBUTE

b) newFaceID &= ~DISABLED_ATTRIBUTE;

The & is a bitwise AND and ^ is a bitwise exclusive OR operator. This is all I knew about this. But, I dont understand the ~DISABLED_ATTRIBUTE and what happens in the assings of the values.

This piece of code is from GWT com.google.gwt.user.client.ui.CustomButton class.

Thanks in advance.

Upvotes: 3

Views: 246

Answers (5)

erickson
erickson

Reputation: 269647

There must be a bit in the ID that is reserved for the hover status. The expression getCurrentFace().getFaceID() ^ HOVERING_ATTRIBUTE appears to toggle the hovering attribute of the current face. In other words, if the HOVERING_ATTRIBUTE bit is one, it is set to zero; if it's zero, it is set to one.

Another bit must be the disabled status. The expression newFaceID &= ~DISABLED_ATTRIBUTE clears this bit. That is, the DISABLED_ATTRIBUTE bit is set to zero.

Upvotes: 2

Mike Nakis
Mike Nakis

Reputation: 61969

The line with the ^ is toggling the bit that HOVERING_ATTRIBUTE stands for. If the bit was 1, it makes it 0; if the bit was 0, it makes it 1.

The line with the &= ~ is clearing the bit that DISABLED_ATTRIBUTE stands for. No matter what the value of the bit was before that, the bit will now be 0.

The ~ thingie alone inverts all the bits of DISABLED_ATTRIBUTE, so the result is what we call a bit-mask suitable for ANDing: the bit that DISABLED_ATTRIBUTE stands for becomes 0, and all other bits become 1. So, if you AND any value with this mask, the result is that this bit will be cleared, and all other bits will remain unaffected.

Upvotes: 3

Zoltán Ujhelyi
Zoltán Ujhelyi

Reputation: 13858

This is good old C-style bitmasking. The FaceID integer number stores a set of bits that represent the selected boolean attributes.

E.g. HOVERING_ATTRIBUTE is 2, DISABLED_ATTRIBUTE is 4.

By running a bitwise xor (^) and a bitwise not (~) it is possible to set or unset these two bits, while keeping other bits intact.

Upvotes: 1

Zéychin
Zéychin

Reputation: 4205

~ is bitwise NOT.

It will reverse each of the bits of DISABLED_ATTRIBUTE.

Upvotes: 1

Makoto
Makoto

Reputation: 106400

~ is a bitwise NOT operator in Java.

In total, the operation in b) is that it takes the NOT of DISABLED_ATTRIBUTE, ANDs it with newFaceID, and assigns it to newFaceID (which is a masking operation).

Upvotes: 1

Related Questions