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?

2
  • 1
    0b01+ 0b10 = 0b11 = 3 (base 10). What are you asking?
    – Carl Norum
    Jun 25, 2012 at 17:09
  • maybe he meant 1 + 2 ;) Apr 7, 2019 at 2:53

1 Answer 1

24
uint16_t value = (highByte << 8) | lowByte ;
7
  • Watch out for endian problems.
    – Carl Norum
    Jun 25, 2012 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, 2012 at 17:15
  • @carl I have changed the variable names to reflect the high and low bytes.
    – diederikh
    Jun 25, 2012 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, 2012 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, 2012 at 17:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.