I have the following code that " functions " in that I can write a 32 bit counter value and place it in the High and Low words of the 32 bit register in a dsPic. I am using MPLAB X IDE and the XC16 compiler.
int main()
{
unsigned long My_Number; // 32 bit
unsigned int High_Word; // 16 bit
unsigned int Low_Word; // 16 bit
My_Number = 0x6000C000; // Decimal 1610661888
High_Word = (My_Number & (0x1FFFF << 16)) >> (16); // Returns 6000
Low_Word = (My_Number & 0xFFFF ) ; // Returns C000
return 0;
}
What I am not understanding is why I need to use 1FFFF to mask the High_Word.
I have tried different values to find what gets returned to find an explanation but something is not clicking and I don't like having anything that works without understanding why as that always leads to issues down the line.
Edit: Having read all the replies and done some re-thinking I have realised that rather than using 1FFFF I could have used FFFFUL to force it to an unsigned long integer and that works. Going further I can see that rather than shifting left to then shift right I could just use
High_Word = (My_Number >> 16);
Low_Word = My_Number;
This code returns the expected values and I believe is more compliant.
This makes no sense and it may invoke undefined behaviour if
sizeof(int) <= 4.I believe that the original programmer simply hit
1by mistake when typing the function. Another clue is that he was thinking about signed numbers not really understanding how they work. Maybe he wanted to enforce 32bit integer constant (if ints are 16bits long), but in this case this code invokes undefined behaviour; Basically, do not take this code as anything goodhttps://godbolt.org/z/Eh45KqEMe