Which way would be best to do it? I think bitshift should be good
With a 32-bit int/unsigned
, all below are the same function and a compiler can emit the same code.
uint8_t first, second;
...
uint16_t combined = (first << 8) + second;
uint16_t combined = (first << 8) | second;
uint16_t combined = (first << 8) ^ second;
uint16_t combined = (first * 256) + second;
uint16_t combined = (first * 256) | second;
....
What is "best" is likely "any of the above" given the compiler is a good one.
For me, I would code as the below if I felt the compiler is potentially weak.
uint16_t combined = ((unsigned)first << 8) | second;
Else I would code to what makes sense for the larger code and clarity. If arithmetic in nature, then the following:
uint16_t combined = (first * 256u) + second; // recommended
Lastly I might try a union
trick to compel a weak compile, but such micro-optimizations are of dubious performance benefits vs. maintenance effort.
With a 16-bit int/unsigned
, best to avoid int
overflow.
uint16_t combined = ((uint16_t)first << 8) | second;
uint16_t combined = (first * 256u) + second;