-9

I have an Arduino sketch, which is basically c++, that has these lines of code in it:

uint32_t cardid = uid[0];
cardid <<= 8;
cardid |= uid[1];

The Arduino is connected to a pn532 RFID reader so basically it scans the card that comes in range and prints the UID on it.
But I cannot understand what the operators |= and <<= do.
I found online that they have something to do with valarrays but I have never used such things.

Chips
  • 117
  • 3
  • 10

3 Answers3

3

In general these operators are shortcuts:

a <<= b   -->   a = a << b
a |= b    -->   a = a | b

In the given example, this code generates a 16 bit value from two 8 bit values. Given

uid[0] = 0x12
uid[1] = 0x34

then

uint32_t cardid = uid[0];  // cardid is now 0x12
cardid <<= 8;              // shifts the value 8 bits to the left -> 0x1200
cardid |= uid[1];          // applies the OR operator -> 0x1200 | 0x34 = 0x1234
koalo
  • 2,113
  • 20
  • 31
1

C++ allows += *= |= &= ... so in your case the first one <<= is called right shift assignment operator which is a shortcut of Shifting the bits of the same lValue then assigning the result to it itself:

int a = 7;
a <<= 2;
a = a << 2; // This line is identical to the one above.

The second |= is called Bitwise Or Assignment operator which is a shortcut of bitwise Or-ing the bits of the same lValue and then assign the result to it itself:

int a = 7;
a |= 2;
a = a | 2; // This line is identical to the one above.
  • Both of the operators works on bits.
Raindrop7
  • 3,889
  • 3
  • 16
  • 27
0

These are bitwise operators (written as shortcuts).

cardid <<= 8; is same as cardid = (cardid << 8); This does an arithmetic left shift, that is essentially multiplying by 2^8 in this case.

cardid |= uid[1]; is same as cardid = (cardid | uid[1]); This performs bitwise OR, that is, it sets in bits in cardid which are also set in uid.

Vasudha
  • 21
  • 3