compiler does not use two's complement ?

Go To Last Post
2 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

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?

 

 

 

 

 

 

 

 

 

This topic has a solution.
Last Edited: Mon. May 23, 2022 - 01:58 AM
This reply has been marked as the solution. 
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

oops, never mind. my temp was was a unsigned char... disregard.