Print signed int

Gary

Well-known member
Hi

Sometimes Im a little confused and the smallest solution seems to be the biggest problem.

For example I have a hex number FFFF and I want to print it on a display. I need to print it with the sign in front. So this should be a signed int.

signed int FFFF should be a negative number.

signed int count = 0xFFFF;
display.print (count);

But if I print it on the display, I get 65535.

What do I wrong?

Thanks a lot

Gary
 
There is no signed hexadecimal format support that I know of. However, it is simple to implement:
Code:
    if ((int16_t)value < 0) {
        display.print("-");
        display.print((uint16_t)(-(int16_t)value), HEX);
    } else {
        display.print("+");
        display.print((uint16_t)value, HEX);
    }
The idea is that you print the sign –– you can omit the plus sign print line if you only want negative sign for negative values ––, and then the magnitude in hexadecimal.

If display does not support the two-parameter form (like Arduino print interface does), then you need to format it into a string, then print that string. It is only a few more lines added to above; let me know if you need that.
 
First I have tried it with int32_t. But the result was not ok. The tip with the right declaration (int16_t) is the right solution.

Thank a lot for your answers. I don't think I would have ever found the solution.

Gary
 
Back
Top