This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

problem adding integer

why result different?

sample 1:

unsigned int index;

char getch()
{
while (!RI);
RI = 0;
return SBUF;
}

index = getch();
index += getch() * 0x0100;

serial port received 2 bytes which are same 0xE8 and result in index is 0xE7E8.

sample 2:

unsigned char ww;

ww = getch;
index = ww;
ww = getch;
index += ww * 0x0100;

result is 0xE8E8.

Parents
  • getch() returns a signed character, so 0xE8 is treated as a negative value.
    When you copied 0xE8 into index, the conversion to an integer extended the sign into the upper byte, making it 0xFFE8
    0xFFE8 + 0xE8 = 0xE7E8.

    In sample 2, you copied the signed char value into an unsigned char variable, so avoiding the sign extension later on.

    Use a type cast to get your desired result, e.g. change:

    index = getch();
    to
    index = (unsigned char) getch();

Reply
  • getch() returns a signed character, so 0xE8 is treated as a negative value.
    When you copied 0xE8 into index, the conversion to an integer extended the sign into the upper byte, making it 0xFFE8
    0xFFE8 + 0xE8 = 0xE7E8.

    In sample 2, you copied the signed char value into an unsigned char variable, so avoiding the sign extension later on.

    Use a type cast to get your desired result, e.g. change:

    index = getch();
    to
    index = (unsigned char) getch();

Children