Pointers are MUCH FASTER than shifts and require no processor math.
You create your 2 byte variable and use Pointers to change each byte separately.
Here is an example:
uint16_t myInt; // 2 byte variable
uint8_t *LowByte = (uint8_t*)myInt; // Point LowByte to the same memory address as
// myInt, but as a uint8 (1 byte) instead of a uint16 (2 bytes)
// Note that low bytes come first in memory
uint8_t *HighByte = (uint8_t*)myInt + 1; // 1 byte offset from myInt start
// which works the same way as:
uint8_t *HighByte = LowByte + 1; // 1 byte offset from LowByte
In some compilers the pointer syntax is a little different (such as Microsoft C++):
uint16_t myInt; // 2 byte variable
uint8_t *LowByte = (uint8_t*)&myInt; // Point LowByte to the same memory address as
// myInt, but as a uint8 (1 byte) instead of a uint16 (2 bytes)
// Note that low bytes come first in memory
uint8_t *HighByte = (uint8_t*)&myInt + 1; // 1 byte offset from myInt start
The *
char in type definition indicates you are creating a pointer, not a variable. The pointer points to a memory address instead of it´s value. To write or read the value of the variable pointed to, you add *
to the variable name.
So, to manipulate the full 2 bytes together, or separately, here are some examples:
myInt = 0x1234; // write 0x1234 to full int
*LowByte = 0x34; // write 0x34 to low byte
*HighByte = 0x12; // write 0x12 to high byte
uint8_t x = *LowByte; // read low byte
uint8_t y = *HighByte; // read high byte
uint16_t z = myInt; // reads full int