This week's book giveaway is in the Performance forum.We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!

# How to understand the sign "|="?

qingwu wang
Ranch Hand
Posts: 147
Hello everybody,the following code snippet come from the ode of lucene2.3.
How to understand the sign "|="? Thanks a lot.

Sagar Rohankar
Ranch Hand
Posts: 2907
1
The operator is OR operator (" | ") ,

| (Bitwise OR) sets a bit to 1 if one or both of the corresponding bits in its operands are 1, and to 0 if both of the corresponding bits are 0. In other words, | returns one in all cases except where the corresponding bits of both operands are zero.(that means , both bits are ZERO , then it ZERO ) The resulting bit pattern is the "set" (1 or true) bits of any of the two operands. This property is used to "set" or "turn on" a "flag" (bit set to one) in your flags or options variable regardless of whether that flag was set previously or not. Multiple flag bits can be set if a combo MASK is defined.

// To set or turn on a flag bit(s)

// or, more succinctly

Regardz,

Rob Spoor
Sheriff
Posts: 20552
57
You'll also have to understand binary a bit, and how integers are represented in binary.

Basically, an integer is a 32 bit number, with the most left bit indicating if the number is positive (0) or negative (1).

So let's take 7 | 26

07 = 0000 0000 0000 0000 0000 0000 0000 0111
26 = 0000 0000 0000 0000 0000 0000 0001 1010

The result is 31:
31 = 0000 0000 0000 0000 0000 0000 0001 1111

Now the most used case is as in Lucene, where every number you add represents a different bit.

0x01 = 0000 0000 0000 0000 0000 0000 0000 0001
0x02 = 0000 0000 0000 0000 0000 0000 0000 0010
0x04 = 0000 0000 0000 0000 0000 0000 0000 0100
0x08 = 0000 0000 0000 0000 0000 0000 0000 1000
0x10 = 0000 0000 0000 0000 0000 0000 0001 0000
0x20 = 0000 0000 0000 0000 0000 0000 0010 0000

So if you | those, you get a number for which each bit represents a setting.

| has a close relative in &. While | results in 0 only if both bits are 0, & results in 1 only if both bits are 1. You can use that to check if a specific bit is set:
if (bits & IS_INDEXED == 0) // IS_INDEXED is not set
if (bits & STORE_TERMVECTOR == 0) // STORE_TERMVECTOR is not set

qingwu wang
Ranch Hand
Posts: 147
These are very helpful for me.
Thanks very very much.