9

I working with serial frames. I'm receiving a 16-bit value as two separate 8-bit values. How can I merge buffer[0] with buffer[1]? I don't want 0b01+0b10 = 12 (base 10). I want it to equal 258.

How can I accomplish this?

Dan F
  • 17,654
  • 5
  • 72
  • 110
Jay Kim
  • 843
  • 4
  • 12
  • 28

1 Answers1

24
uint16_t value = (highByte << 8) | lowByte ;
diederikh
  • 25,221
  • 5
  • 36
  • 49
  • Watch out for endian problems. – Carl Norum Jun 25 '12 at 17:12
  • This answer is correct, assuming that it is known that `byte1` is the high byte, and `byte2` is the low byte – Dan F Jun 25 '12 at 17:15
  • @carl I have changed the variable names to reflect the high and low bytes. – diederikh Jun 25 '12 at 17:16
  • @TJD: I see no reason why not, the result will not fit a uint8_t of course. Just try it out. – diederikh Jun 25 '12 at 17:21
  • @TJD - that's not true. Just as with many other C operators, the integer promotions are performed before the operation takes place. – Carl Norum Jun 25 '12 at 17:25
  • @CarlNorum, I know in practice it may work, but isn't it actually undefined behavior?: http://stackoverflow.com/questions/3482262/bitshift-and-integer-promotion – TJD Jun 25 '12 at 17:32
  • @TJD - no, it's explicitly defined. The answer to your linked question is a little confusing. From the C spec, **6.5.7 Bitwise shift operators**, paragraph 3: "The integer promotions are performed on each of the operands." The problem comes when the shift amount is greater than the size of the *promoted* operand: "If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined." Unless the OP has an 8-bit `int` type, he's going to be fine. – Carl Norum Jun 25 '12 at 17:59