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.
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();
index = (unsigned char) getch();
Oops, typo in the previous post.
0xFFE8 + 0xE8 = 0xE7E8
0xFFE8 + 0xE800 = 0xE7E8 (with carry)