What’s the type of the variable temperature
? The function highByte
is documented as:
Extracts the high-order (leftmost) byte of a word (or the second lowest byte of a larger data type).
Now, if temperature
has a size of more than 2 bytes (1 word), you’ll be missing information, and will also show wrong results for large positive values then. It’s safer to be more explicit about the specific byte you’re including then. Also, it needs to be defined as some signed integer value, so something like int_16t temperature
.
With the signed integer -10 being stored in memory as 0xFFF6 or 0xFFFF FFF6 (when showing as hexadecimal), and assuming mydata
is defined as byte[]
or uint8_t[]
:
int_16t temperature = -10;
uint8_t mydata[4];
// Handle high byte (MSB) first; 0xFF for -10
// 0xFFF6 >> 8 shifts the 0xF6 out of memory, leaving 0x00FF
// 0x00FF does not fit in a single byte, so only 0xFF is stored in mydata[2]:
mydata[2] = temperature >> 8;
// Handle low byte (LSB) next; 0xF6 for -10
// 0xFFF6 does not fit in a single byte, so only 0xF6 is stored in mydata[3]:
mydata[3] = temperature;
This should work, but is confusing: bytes[2]
is not only the sign, but is really part of the value. Also, using the bitwise OR
rather than the mathematical addition, saves the need for some parentheses. So, I’d use a single line:
// Sign-extend to 32 bits to support negative values, by shifting 24 bits
// (16 too far) to the left, followed by a sign-propagating right shift:
var temp = bytes[2]<<24>>16 | bytes[3];
This is the same as:
bytes[0]<<24>>16 | bytes[1]