Question on Data Byte and Word Manipulation
I am used to using Keil C51 on 8051 8 bit CPU's. Keil treats 16 bit and 32 bit data types as "Big Endian". The Luminary (TI) Cortex-M3 parts are hard locked to "Little Endian".
My problem is this: In my 32 bit data, I regularly need to access specific 8 bit or 16 bit sections of the 32 bit data. I can do this with on the 8051 with Keil using a pointer such as:
ByteWanted = *(char*)&LongData; // Gets me Most Significant Byte
or
ByteWanted = *(((char*)&LongData)+3); // Gets me Least Significant Byte
If I try this on the Little Endian Cortex then I get the opposite byte. This has caused me a big portable code issue.
My question is this: Is there an easier way to access the individual bytes using Crossworks, "C" and/or Arm architecture? I could Mask and Shift but that will be CPU Cycle intensive. I could re-write it to index my bytes in the opposite way to what I have been doing but then I would have the same problem as I have now if I tried to port it to a different architecture.
Any suggestions?
Thanks in Advance
Steve
-
Use shift operator >>
ByteWanted = (unsigned char)((LongData >> 0) & 0xff); //Always gets least significant byte
ByteWanted = (unsigned char)((LongData >> 24) & 0xff); //Always gets most significant byte
This works no mater what endian the CPU is.
Here are the macros I use:
#define word_get_low_byte(val) ((unsigned char)((val) & 0xFF))
#define word_get_high_byte(val) ((unsigned char)(((val)>>8) & 0xFF))
#define dword_get_low_byte(val) ((unsigned char)((val) & 0xFF))
#define dword_get_mlb_byte(val) ((unsigned char)(((val)>>8) & 0xFF))
#define dword_get_mhb_byte(val) ((unsigned char)(((val)>>16) & 0xFF))
#define dword_get_high_byte(val) ((unsigned char)(((val)>>24) & 0xFF))
Please sign in to leave a comment.
Comments
3 comments