Thanks a million Pete, it works a treat!
Apart from fixing the issue I'm struggling to understand the syntax used in the last part
What does "?" do as I have never seen this used as a bitwise operator.
How does "0xFFFF0000:0" differ from "0xFFFF0000" Not understanding the "
" part. Sorry I can't stop from making an angry face but I think you know what I mean
The colon part is part of the ternary operator ?:, and not part of the integer constant:
The ternary operator tests test
, and if it is non-zero (true), it returns true_value
, else if it is 0 (false), it returns false_value
test ? true_value : false_value
So in the example:
((MSB_z & 0x80) ? 0xFFFF0000:0 )
If MSB_z has the top bit in the lower 8-bits set, it will or in all 1's in the upper 16-bits, which given MSB_z is put into the bits just before it, will sign extend the value.
Another way to write the code is:
return (((int)(int8_t)MSB_z) << 8) | LSB_z;
cast first converts MSB_z to be a signed 8 bit type, and then the (int)
cast converts that type to the default int size (16-bits on AVRs, 32-bits on ARMs). Or instead of int8_t
, you can use signed char
, which is the same thing on most modern machines. There were machines in the past that had different sized chars than 8 bits (but most of those machines predated the int<n>_t and uint<n>_t types that are defined in the Arduino environment.