5 years, 5 months ago.

Split 16 bit integer value.

How do I split a 16 bit integer value to 2 bytes?

1 Answer

5 years, 5 months 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

Accepted Answer

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);
}
posted by Zoltan Hudak 29 Oct 2018