I was having a browse through the book ‘Programming 16-bit Microcontrollers in C. Learning to Fly the PIC24‘ by Lucio Di Jasio.Leaving aside for now the tendency for authors to use overlong titles, there seems to me some interesting stuff in there. Early on there is a bit about what happens when you assign an int to a long as in this code fragment:

int intvar;
long longvar;
longvar = intvar;

In the book it says that the int is copied into the lower 16 bits of the long and the upper 16 bits are filled with zeros. Well, Iwould hope not. At the very least, I would expect that the sign would be extended into the upper 16 bits. After bashing this code into a file in MPLAB, I compiled it and looked at the generated assembly code. In fact, what the compiler does is to multiply the int by 1 and assign the resulting 32bit value to the long. This will have the desired effect. I have not bothered to see if the dsPIC has a sign extend instruction but clearly the compiler thinks this is the most efficient way to do the job.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.