How does the pipe (|) operator work in Android while setting some properties?

Ichigo Kurosaki :

My question may be basic, but I am wondering how the pipe operator works in the following contexts in Android :

We can set multiple input types in layout:

android:inputType = "textAutoCorrect|textAutoComplete"

We can set multiple flags to an intent as follows:

intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION|Intent.FLAG_ACTIVITY_CLEAR_TOP);

Also we can set some properties as follows:

tvHide.setPaintFlags(tvHide.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

There are multiple instances where we can see such examples in Android.

So my question is, does the | operator act like the bitwise OR operator or does it just concat the results or something else?
If it acts like the bitwise OR operator, then how does it make the expected result correct? Can anybody enlighten me on this?

Michael Dodd :

Yes, it is a bitwise inclusive OR operation, primarily used for setting flags (documentation). Consider the following flags:

byte flagA = 0b00000001;
byte flagB = 0b00000100;

If we use the | operator, these two flags are combined:

byte flags = flagA | flagB; // = 0b00000101

Which allows us to set properties or other small bits of status information in a small amount of memory (typically an Integer with most Android flags).

Note that a flag should only ever have one bit "active", i.e. have a value equal to 2^n. This is how we know what flags have been set when we go to check the combined flag holder variable using a bitwise AND operator, e.g.

if ((flags & flagA) == flagA) {
    // Flag A has been set
    ...
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=467765&siteId=1