Working with avr studio 6.2 and a atmega32u4.
I ran some code on a simulator.
int main() { unsigned char n = 10- 5; unsigned char n2 = 5- 10; unsigned char n3 = 10- 5; n3 = ~n3; n3 ++; for (int c = 7; c >= 0; c--) { int k = n >> c; if (k & 1) printf("1"); else printf("0"); } printf("\n"); for (int c = 7; c >= 0; c--) { int k = n2 >> c; if (k & 1) printf("1"); else printf("0"); } printf("\n"); for (int c = 7; c >= 0; c--) { int k = n3 >> c; if (k & 1) printf("1"); else printf("0"); } return 0; }
my output was what I expected.
00000101
11111011 <-- subtracting
11111011 <-- flipping and adding 1
but on my avr this does not yield the same results.
working code
unsigned char mouseX_now = reportBuffer[X_MAIN_STICK]; if (mouseX_now > mouseX_old) temp = (mouseX_now - mouseX_old); else temp = (mouseX_old - mouseX_now); if (mouseX_now <= mouseX_old) { temp = ~temp; temp ++; }
but why will this not work?
unsigned char mouseX_now = reportBuffer[X_MAIN_STICK]; temp = (mouseX_now - mouseX_old);
the values are not inverted, and I'm not %100 what the compiler is doing but the result is wrong. Should the subtract not use two complement, is it byte promoting or something? Do I need a cast?