Take the 2-minute tour ×
Electrical Engineering Stack Exchange is a question and answer site for electronics and electrical engineering professionals, students, and enthusiasts. It's 100% free, no registration required.

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?

share|improve this question
1  
The question is not related to electrical engineering, this should have been posted in stack overflow –  alexan_e Dec 10 '13 at 8:00
add comment

2 Answers

up vote 8 down vote accepted

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.

share|improve this answer
    
Thank You @PeterJ –  Rookie91 Dec 10 '13 at 4:04
add comment

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.

share|improve this answer
2  
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. –  markt Dec 10 '13 at 6:03
    
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. –  Joe Hass Dec 10 '13 at 12:12
    
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. –  Myforwik Dec 15 '13 at 2:20
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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