22

What is the meaning of <<= and |= in C?

I recognise << is bitshift etc. but I don't know what these are in combination.

Chris Cooper
  • 17,276
  • 9
  • 52
  • 70
Ken
  • 30,811
  • 34
  • 116
  • 155

1 Answers1

37

Just as x += 5 means x = x + 5, so does x <<= 5 mean x = x << 5.

Same goes for |. This is a bitwise or, so x |= 8 would mean x = x | 8.

Here is an example to clarify:

int x = 1;
x <<= 2;         // x = x << 2;
printf("%d", x); // prints 4 (0b001 becomes 0b100)

int y = 15;
y |= 8;          // y = y | 8;
printf("%d", y); // prints 15, since (0b1111 | 0b1000 is 0b1111)
roschach
  • 8,390
  • 14
  • 74
  • 124
Chris Cooper
  • 17,276
  • 9
  • 52
  • 70