Combining two uint8_t as uint16_t

前端 未结 4 1746
迷失自我
迷失自我 2021-02-02 11:13

I have the following data

uint8_t d1=0x01; 
uint8_t d2=0x02; 

I want to combine them as uint16_t as

uint16_t wd =         


        
4条回答
  •  Happy的楠姐
    2021-02-02 11:58

    This is quite simple. You need no casts, you need no temporary variables, you need no black magic.

    uint8_t d1=0x01; 
    uint8_t d2=0x02; 
    uint16_t wd = (d2 << 8) | d1;
    

    This is always well-defined behavior since d2 is always a positive value and never overflows, as long as d2 <= INT8_MAX.

    (INT8_MAX is found in stdint.h).

提交回复
热议问题