Which CPU are you compiling for?
Try this. The theory is that the compiler is assuming that an 8-bit quantity left-shifted by 8 bits is always 0. (this is wrong, AFAIK. Values in expressions are always supposed to be promoted to "int" before calculations, if not otherwise specified. But that frequently results in bad code for 8bit quantities, so it's somewhat understandable that it could be done wrong, especially in a compiler with "optimizations disabled" (I assume you're using the free version of C18?))
- Code: Select all
nValue = (((unsigned int)(array[1]) << 8) + array[0];
I tried this in MPLAB X and it seems to produced more correct-looking code (awful code, but more correct looking.)
Personally, I'd look for a different "free" or cheap compiler. The limitations that the Microchip-provided compilers insist upon are too ... limiting. I'd much rather have a 32k (or smaller) code limit than a "produces awful and obscure code"
BTW, unless you're aiming for specific endianness that is different from the default (and your example looks like the default, the usual hack is something like:
- Code: Select all
nValue = *(int*)(&array[0]);
That says: even though this is a character array, I'm telling you that there are ints there, and you should go and get them!