johan
johan

Reputation: 1983

Combining two uint8_t as uint16_t

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 = 0x0201;

How can I do it?

Upvotes: 35

Views: 67557

Answers (4)

fizzbuzz
fizzbuzz

Reputation: 157

(uint16_t)((d2 << 8) + (d1 & 0x00ff))

Upvotes: 3

Lundin
Lundin

Reputation: 213720

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).

Upvotes: 11

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215241

The simplest way is:

256U*d2+d1

Upvotes: 16

md5
md5

Reputation: 23699

You can use bitwise operators:

uint16_t wd = ((uint16_t)d2 << 8) | d1;

Because:

 (0x0002 << 8) | 0x01 = 0x0200 | 0x0001 = 0x0201

Upvotes: 57

Related Questions