how convert two bytes into one 16-bit number?

23,307

Solution 1

The math works out as follows:

sixteenBitNumber = 256*upperByte + lowerByte;

with shifts and bitwise operations:

sixteenBitNumber = (upperByte<<8) | lowerByte;

In most CPUs, even some archaic 8-bit ones, this interpretation is done in hardware: you load bytes into parts of a 16-bit register or into separate 8-bit registers that can work as a 16-bit pair, and the hardware works with the data as if it were a single 16-bit number.

Solution 2

In decimal how do I take 7 and 9 and make 79? (7*10)+9 Or 12 and 34 and make 1234? (12*100)+34. No different 0x12 and 0x34 and make 0x1234. (0x12 * 0x100) + 0x34. Much cleaner to bit shift (0x12 << 8 ) + 0x34. you can or it is as well (0x12<<8) | 0x34.

Share:
23,307
Jay Kim
Author by

Jay Kim

Updated on October 15, 2020

Comments

  • Jay Kim
    Jay Kim over 3 years

    I understand that 1 byte will hold a number from 0-255. And that a 16-bit number is between 0-65535.

    If I'm trying to represent a 16-bit number using two separate 8-bit registers...how do I do that? How does the math work?

    Thanks!