This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Accessing bytes of long data type

I know that longs are stored MSB first in memory. I need to access individual bytes of a long in order to send them out the SPI port. There are a number of ways to do this, I'd like your opinion on which approach might be best (from whatever perspective).

Two that come to mind is to simply declare the variable as a long pointer and then access each byte using the pointer. Pretty clean as far as I am concerned, but don't know if there's a better C51 way to handle this task.

Another --more convoluted, maybe even ugly-- is to avoid direct memory access and simply rotate/mask the long and cast into an unsigned char four times to grab each byte. Ugly at best.

Thanks,

-Martin

Parents
  • Hi Martin,

    Although you are aware that the MSB is stored 1st, I think that your second idea of shifts and casting is the safer option because programmers who are not as familiar with the 8051 may not easily be able to see the order that you are sending the data out via the SPI (ie. is LSB->MSB or MSB->LSB and yes well commented code should make it self explanatory whatever method you use).
    Also because you are passing longs to functions, as they are alredy in 4 registers the compiler may actually generate more efficient code because it will effectivly be just loading each reg into the SPI without any need to do the shifts/masking or 'messing' with pointers to retreive each of the the bytes making up the long.

    Mark.

Reply
  • Hi Martin,

    Although you are aware that the MSB is stored 1st, I think that your second idea of shifts and casting is the safer option because programmers who are not as familiar with the 8051 may not easily be able to see the order that you are sending the data out via the SPI (ie. is LSB->MSB or MSB->LSB and yes well commented code should make it self explanatory whatever method you use).
    Also because you are passing longs to functions, as they are alredy in 4 registers the compiler may actually generate more efficient code because it will effectivly be just loading each reg into the SPI without any need to do the shifts/masking or 'messing' with pointers to retreive each of the the bytes making up the long.

    Mark.

Children
  • That's an interesting point. I'm trying to stay as "C-like" as possible with this project. I have twenty+ years of assembler-based embedded work under my belt...but all my C/C++ work has been in application coding on desktop systems. This is my first embedded-C project, which is actually a translation of an existing ASM app to C. It's very different when you have the restrictions of an 8051 to contend with.

    Thanks for your help.