Should I prefer addition or logical OR operator if both would give the same result?
-
04-07-2021 - |
Pergunta
Should I prefer +
(addition) operator or |
(or) operator if both would give the same result?
I understand that addition and logical OR are different things. But they sometimes do the same thing in some macros, especially when playing with bytes and bits. Which one should I prefer in this case?
Example:
uint8_t Byte1 = 0x02; // 0000 0010
uint8_t Byte2 = 0x80; // 1000 0000
uint16_t Word1, Word2; // 0000 0010 1000 0000 = 640 = 0x0280
Word1 = (Byte1 << 8) + Byte2;
Word2 = (Byte1 << 8) | Byte2;
std::cout << "Word1 = " << Word1 << std::endl;
std::cout << "Word2 = " << Word2 << std::endl;
Output:
Word1 = 640
Word2 = 640
Solução
When manipulating bit patterns, logical operators are appropriate. When manipulating numeric values, arithmetic operators are appropriate.
Outras dicas
I would avoid mixing bit operations and arithmetic operations in the same expression, so I would write
Word1 = (Byte1 * 256) + Byte2;
but
Word2 = (Byte1 << 8) | Byte2;
Readability is the only thing to worry about here, because a good optimizer should produce the same exact code for both expressions.