8bit operations are always compiled into 16bit instructions #361
Labels
conclusion: invalid
Issue/PR not valid
topic: code
Related to content of the project itself
type: imperfection
Perceived defect in any part of project
After refactoring my code so that all unsigned long I used for managing timestamp became uint8_t in order to save memory and time, I realized that an operation uint8_t - uint8_t could give as result a negative number (e.g. -252); that was very strange for two reasons:
I tried investigating and I found out that, not only the operations that can have overflows or underflows (i.e. sum, subtraction, multiplication, logical left shift, etc.), but also those that are guaranteed, given two 8bit operands, to have an 8bit result (i.e. bitwise and, bitwise or, logical right shift, division, etc...) are always executed as 16bit instructions.
I tried to find the origin of this problem and I came across this stackoverflow question: summarazing, on 32bit machines, of course, nbit operations (with n<32) need operands to be 32bit and that's why an uint8_t or a uint16_t difference can give a negative result.
This was partially fixed in the arduino-builder, since uint16_t difference gives a uint16_t result, but of course 8bit operands are still transformed into 16bit numbers: this would be correct if and only if ATmega328P was a 16bit microcontroller, but of course it's an 8bit microcontroller with instructions for handling natively 16bit operations (e.g. a 16 bit sum is done with one add and one adc).
This issue can bring many problems such as:
The text was updated successfully, but these errors were encountered: