1

What is the below Arduino code doing?

I am not familiar with the '+' with regard to bitwise operations. Just getting familiar with this stuff.

return ((four << 0) & 0xFF) + ((three << 8) & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF);
jsotola
  • 1,554
  • 2
  • 12
  • 20
fmarquet
  • 33
  • 5

2 Answers2

2

+ is the addition operator. It is used to add numbers. For example, 2+3 yields 5.

For analyzing your expression, let's call “a”, “b”, “c” and “d” the bits of one, two, three and four respectively, like this:

one    = aaaaaaaa
two    = bbbbbbbb
three  = cccccccc
four   = dddddddd

These numbers may have more than 8 bits, but in that case the extra bits will be discarded by the & operations. Now, let's compute the terms of the sum, and then the whole sum:

(one   << 24) & 0xFFFFFFFF = aaaaaaaa000000000000000000000000
(two   << 16) & 0x00FFFFFF = 00000000bbbbbbbb0000000000000000
(three <<  8) & 0x0000FFFF = 0000000000000000cccccccc00000000
(four  <<  0) & 0x000000FF = 000000000000000000000000dddddddd
─────────────────────────────────────────────────────────────
sum                        = aaaaaaaabbbbbbbbccccccccdddddddd

As you see, only one bit in each column of this addition can be non-zero, and that column's sum can only be 0 or 1. This means that there will be no carries, and the columns will add independently of one another. The sum is then made of the bits of one, two, three and four concatenated.

The exact same result could be computed by using the bitwise OR operator (|) instead of +. In fact, I would prefer using |: to my eyes it makes the programmer's intent clearer.

Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81
1

You are better off using | for bitwise operations. Whilst + will work under certain circumstances, | is better. For example:

a = 1 + 1 + 1 + 1;  // a will be 4
a = 1 | 1 | 1 | 1;  // a will be 1

For code where you are just trying to set a single bit, using | is much preferable, as if the bit is already set and you use + then you will clear the bit and set the next one along.

Nick Gammon
  • 38,901
  • 13
  • 69
  • 125