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.
The size of the long type is 8 bytes (64 bits).
Pointers. The ARMv7-M architecture used in mbed microcontrollers is a 32-bit architecture, so standard C pointers are 32-bits.
CP1 = (CurrentPosition & 0xff000000UL) >> 24;
CP2 = (CurrentPosition & 0x00ff0000UL) >> 16;
CP3 = (CurrentPosition & 0x0000ff00UL) >> 8;
CP4 = (CurrentPosition & 0x000000ffUL) ;
You could access the bytes through a pointer as well,
unsigned char *p = (unsigned char*)&CurrentPosition;
//use p[0],p[1],p[2],p[3] to access the bytes.
I think you should consider using a union:
union {
unsigned long position;
unsigned char bytes[4];
} CurrentPosition;
CurrentPosition.position = 7654321;
The bytes can now be accessed as: CurrentPosition.bytes[0], ..., CurrentPosition.bytes[3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With