Reputation: 23
I'm using Arduino with ESP32 and I'm still at the beginner level. I have two bytes which are uint8 and are variables, I want to convert them to uint16. Which way would be best to do it? I think bitshift should be good
uint8_t first = 0xFF; //lets assume its variable, not constant
uint8_t second = 0xEE;
uint16_t combined = (first << 8) + second;
Serial.println(combined, HEX); // prints FFEE
The code above does the job, but I'm not sure is it the right/best way.
Upvotes: 1
Views: 3395
Reputation: 153508
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;
Upvotes: 1