I'm trying to interface to an already written piece of software that requires an 'XXXX' signed hex result.
sending a positive result is not a problem but a negative value is causing me real headache.
If the int is positive if I use, Serial.print(Result, HEX); all is well.
However if the int is to be a negative value I use, Result = Result ^ 0xffff;
the result is now hex FFFFFFxx, where xx is the Result value.
The result is now a 32 bit 2's compliment number and I need a 16 bit one. How do I remove the preceding F's?
I've also tried Result = 65535 - Result; but I still end up with too many F's
I'm sure the answer is very simple I just can seem to see it at the moment.
Amy help would be most welcome.
Jiggy-Ninja
Thanks for the speedy reply my typo should have read Result = (Result ^ 0xffff) +1
I've just tried your rely and I get a positive number in hex.
Basically if my int result is 24 then I can convert it to 0x0018, but if the result is -24 the result I need is 0xFFE7.
or 0xFFFF - 0x0018 or 65535 - 24 = 65511 converted to 0xFFE7.
When I try this in my code I get 0xFFFFFFE7 which the third party software won't accept.
If you change the negative number to a positive number you can't distinguish the two at the receiving end.
The problem is that when printing an integer Serial.print seems to default to a 32 bit-integer so it sign-extends the negative numbers. You can use either this:
Serial.println((uint16_t)result,HEX);
or this:
Serial.println(result & 0xffff,HEX);
to force it to send four hex digits. E.g. -45 will be sent as FFD3 which is the correct HEX representation of the 16-bit twos complement number.