In <Xn**********************************@130.133.1. 4> David Vestal <so****************@mailcity.com> writes:
I'm reading a 24-bit address from a char* named i_msg, and I expected these
two snippets to be equivalent. They aren't; the first doesn't work. What
gives?
You have to throw more parentheses at the problem: the compiler is
blissfully ignoring your nice formatting of the expression and uses the
C precedence rules instead ;-)
SNIPPET 1:
unsigned long address;
address = ((unsigned long) i_msg[2]) << 16
+ ((unsigned short) i_msg[3]) << 8
+ i_msg[4];
This is interpreted as:
(((unsigned long) i_msg[2]) << (16 + ((unsigned short) i_msg[3]))) <<
(8 + i_msg[4])
which probably not what you want. Try the following instead:
address = (((unsigned long) i_msg[2]) << 16)
+ (((unsigned short) i_msg[3]) << 8)
+ (unsigned char) i_msg[4];
Note that, unless plain char is unsigned, the last cast I have added is
needed, too.
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email:
Da*****@ifh.de