Spliting an hex into 2 hex values

前端 未结 3 2167
Happy的楠姐
Happy的楠姐 2020-12-22 06:51

I have a problem I have an Hexadecimal like 0x6002 and I have to split it into 0x60 and 0x02. how do I do that?

I progam in cp

3条回答
  •  -上瘾入骨i
    2020-12-22 07:07

    You can use masking to extract the low byte and a shift to extract the high byte:

    uint16_t a = 0x6002;
    uint8_t a0 = a & 0xff;  // a0 = 0x02
    uint8_t a1 = a >> 8;    // a1 = 0x60
    

    Note that the & 0xff is not strictly necessary for a narrowing unsigned conversion such as that above, but there are other cases where it might be necessary (e.g. when signed conversion is involved, or when the destination type is wider than 8 bits), so I'll leave it in for illustrative purposes.

提交回复
热议问题