-1

Looks like a simple method, but I can't understand how | works here:

/**
 * Bitwise rotate a 32-bit number to the left.
 */
private static int rotateLeft(int x, int n) {

    return (x << n) | (x >>> (32 - n));
}

First part (x << n), where << is binary left shift operator. The left operands x value is moved left by the number of bits specified by the right operand n.

The (x >>> (32 - n)) part, where >>> is shift right zero fill operator. The left operands x value is moved right by the number of bits specified by the right operand (32 - n) and shifted values are filled up with zeros.

But what is the purpose of |?

EDIT: OK, I found that it is simple operator: "binary OR operator copies a bit if it exists in either operand". So the sequence is: (x << n), then (x >>> (32 - n)), then (left part result) | (right part result)?

Ernestas Gruodis
  • 8,567
  • 14
  • 55
  • 117

2 Answers2

4

| is the bitwise OR operation.

It often resembles the plus operator, since its' truth table is:

A  B   A|B
-----------
0  0   0
1  0   1
0  1   1
1  1   1

For example: 8 | 2 = 10 since 8 is 1000 and 2 is 0010 and so:

1000 = 8
0010 = 2
----
1010 = 10
Ori Lentz
  • 3,668
  • 6
  • 22
  • 28
2

A bitwise rotate operation shifts bits to the left, but also "rescues" bits shifted off the high end of the value and shifts them onto the low end. The | operation in that function combines the "lost" bits from the high end of the word — shifted down to the low end — with the remaining bits shifted up.

The shift upwards leaves 0 bits in the low end, so it's assured that the only 1 bits will be those that were set in the high end of the word before the rotation.

Pointy
  • 405,095
  • 59
  • 585
  • 614