4
\$\begingroup\$

I would like to know two things that is making my head quite confusing these days.

If i allocate an int in C18 compiler I know it will take two bytes and, if I initialize a pointer to the variable, say:

int x,*xptr;
xptr = &x;

then I have to access *xptr for first byte and *xptr+1 for the second byte?

Well, what factor determines that which one is MSB and LSB?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ The question is not related to electrical engineering, this should have been posted in stack overflow \$\endgroup\$ – alexan_e Dec 10 '13 at 8:00
8
\$\begingroup\$

The order is defined by the compiler. If you look at the MPLAB C18 C Compiler User's Guide and search for "endianness" on page 12 you'll find:

Endianness refers to the ordering of bytes in a multi-byte value. MPLAB C18 stores data in little-endian format. Bytes at lower addresses have lower significance (the value is stored “little-end-first”).

So in your example *xptr will reference the LSB and *xptr+1 will reference the MSB.

\$\endgroup\$
0
1
\$\begingroup\$

The 'endianness'. Generally speaking - it should not matter.

If you want upper and lower bytes of a word do something like:

unsigned int a = 1234;
unsigned char upper;
unsigned char lower;

upper = (a>>8)&0xFF;
lower = a & 0xFF;

and the reverse:

unsigned char upper = 12;
unsigned char lower = 34;
unsigned int a = 0;
a |= upper;
a <<= 8;
a |= lower;

This will ensure your code works reguardless of the compiler/cpu/endian.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ That is not good coding practice on an embedded system - the compiler is all too likely to do exactly what you have told it to and implement some very expensive (in terms of time & processor cycles) operations. Much better to do as the OP originally suggested. \$\endgroup\$ – markt Dec 10 '13 at 6:03
  • \$\begingroup\$ It would be a very poor compiler indeed that did not convert multiplication and division by 256 into left and right shift operations. However, I agree that this is poor coding practice. If your intention is to shift bits then use a shift operation. If your intention is to merge bit fields then use an OR operation, not an addition. \$\endgroup\$ – Joe Hass Dec 10 '13 at 12:12
  • \$\begingroup\$ I think you are missing the point. It isn't over mul add vs shift/or, its about not assuming endian. I could re-write it with shift/or of course. Once people assume endian, then they start doing things like... assume padding alignment etc. \$\endgroup\$ – Myforwik Dec 15 '13 at 2:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.