Search code examples
javaoperatorsbitbinary-operators

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];
}

Solution

  • 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