MP13
MP13

Reputation: 410

What is the | operator doing in Java?

I read some Java code and came across the | operator. Can anyone what the operator is doing in this context?

for (int i=0; i<8; i++) {
            x[i] = hexBytes[i*4]   << 24
                 | hexBytes[i*4+1] << 16
                 | hexBytes[i*4+2] << 8
                 | hexBytes[i*4+3];
}

Upvotes: 2

Views: 95

Answers (2)

Kayaman
Kayaman

Reputation: 73558

The bitwise OR (and AND) can be used for bit handling. AND allows you to extract a set of bits: int lowest8bits = 0xFFFFF & 0xFF;.

With OR you can insert bits. In the code above, 4 bytes are inserted to the same int by shifting them to the right position and ORing them.

                           10010010 byte
                  10010010 00000000 << 8
00000000 00000000 00000000 00010110 The int we're building
00000000 00000000 10010010 00010110 End result in int after OR

Upvotes: 1

Sandeep Kokate
Sandeep Kokate

Reputation: 845

Operators used are:

  1. "<< (left shift)" : Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
    1. ">> (right shift)" : Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
    2. "| (bitwise or)" : Binary OR Operator copies a bit if it exists in either operand.

In your code:

hexBytes[i*4]   << 24

binary value of hexBytes[i*4] is left shifted by 24 bit. same with others and the result is OR by the bitwise | operator.

Upvotes: 1

Related Questions