Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
7 years ago.
Split 16 bit integer value.
How do I split a 16 bit integer value to 2 bytes?
1 Answer
7 years ago.
Thats pretty basic stuff. Google should know. Try
char lowbyte, highbyte; short int value = 0x1234; lowbyte = value & 0xFF; //mask out lower 8 bits highbyte = (value >> 8) & 0xFF; //shift upper 8 bits and mask
Just for fun's sake :)
int16_t intToSplit = 348;
uint8_t* bytes = (uint8_t*) &intToSplit;
uint8_t byte1 = *bytes;
uint8_t byte2 = *(bytes + 1);
printf("16 bit integet = %d\r\n", intToSplit);
printf("byte1 of int = %d\r\n", byte1);
printf("byte2 of int = %d\r\n", byte2);
or
union MyUnion {
int16_t integer;
struct {
uint8_t byte1;
uint8_t byte2;
};
};
int main()
{
int16_t intToSplit = 348;
MyUnion myUnion;
myUnion.integer = intToSplit;
printf("16 bit integet = %d\r\n", myUnion.integer);
printf("byte1 of int = %d\r\n", myUnion.byte1);
printf("byte2 of int = %d\r\n", myUnion.byte2);
}