I have a 32 bit long variable, CurrentPosition, that I want to split up into 4, 8bit characters. How would I do that most efficiently in C? I am working with an 8bit MCU, 8051 architectecture.
unsigned long CurrentPosition = 7654321;
unsigned char CP1 = 0;
unsigned char CP2 = 0;
unsigned char CP3 = 0;
unsigned char CP4 = 0;
// What do I do next?
Should I just reference the starting address of CurrentPosition with a pointer and then add 8 two that address four times?
It is little Endian.
ALSO I want CurrentPosition to remain unchanged.
I know this was posted some time ago. But for anyone still reading the thread: Many people take the approach of sequentially shifting the original value. Why not let the compiler do the work for you. Use a union & to allow you to store the values in the same location. Define a union consisting of both a 32 bit long variable (this will be where you save your CurrentPosition) and a structure consisting of 4 char variables. Or just a simple 8 bit integer array. When you write your CurrentPosition to the long variable, it will be stored in the same location accessed when you read the 4 char variables. This method is much less labour intensive and does not allows the compiler to do the work instead of wasting time & resources.
Now CPn per your original code is accessed via
CP[n]
.If You are using an 8 bit MCU shifting a whole 32 bit variable is a bit of work. In this case it's better to read 4 bytes of CurrentPosition using pointer arithmetic. The cast:
doesn't change the CurrentPosition, but if You try to write to p[0] You will change the least significant byte of the CurrentPosition. If You want a copy do this:
and work with arr. (If you want most significant byte first change the order in those assignments).
If You prefer 4 variables You can obviously do:
I think you should consider using a union:
The bytes can now be accessed as: CurrentPosition.bytes[0], ..., CurrentPosition.bytes[3]
You could access the bytes through a pointer as well,