priority of operators
Posted: Thu May 09, 2019 7:32 pm
Using 2 bytes words like Uint (0 to 65535) and Int (-32768 to 32767) special care has to be taken if the low- and high byte are needed. This is e.g. in case of using EEPROM (with only bytes).
Say the 2 bytes variable is A and the low byte is A_low and the high byte is A_high.
1) To find the low- and high byte is possible like:
A_high= A>>8
A_low= A & 0xx00FF //(with & is AND)
2) If the low- and high byte are known, then A can be calculated like:
A= (A-high<<8) + A_low.
Comment:
I first did A= A_high<<8+A_low, but find out that gave wrong results. I had the feeling that the priority of << is higher then +. But that is wrong. The priority is shown in the table below of presence of operators.
It shows that operator + has a higher priority (4) compared to the operator << (priority=5)
Conclusion
In the statement A=(A_high<<8)+ A_low the parentheses () are needed. Of course, there is an alternative like:
A= A_high<<8
A=A+ A_low
Kind regards
Jan
Say the 2 bytes variable is A and the low byte is A_low and the high byte is A_high.
1) To find the low- and high byte is possible like:
A_high= A>>8
A_low= A & 0xx00FF //(with & is AND)
2) If the low- and high byte are known, then A can be calculated like:
A= (A-high<<8) + A_low.
Comment:
I first did A= A_high<<8+A_low, but find out that gave wrong results. I had the feeling that the priority of << is higher then +. But that is wrong. The priority is shown in the table below of presence of operators.
It shows that operator + has a higher priority (4) compared to the operator << (priority=5)
Conclusion
In the statement A=(A_high<<8)+ A_low the parentheses () are needed. Of course, there is an alternative like:
A= A_high<<8
A=A+ A_low
Kind regards
Jan