I am trying to take a signed hex number and display it on the terminal as a negative decimal number so that it can be easily read. I am having a hard time working through the logic on how to make this happen. I am using a PIC16F15345 and Real Term as my terminal. My UART is up and running correctly.
Problem Example:
Hex: B6
Display dec value: -74
I have thought about first converting the hex number to binary by creating a large if statement for each byte and then concatenate them together, but I am not quite sure on where to go next for converting to decimal. I need this code to be efficient and easily readable as it is going into some documentation I have and all of my ideas seem very complex and long. I feel like I am overthinking this.
Thank you for the help
B
and a6
, or do you really just have a number in an 8-bit variable in your code? \$\endgroup\$printf
will suffice - or to be safe and correct, probablysnprintf
would be better. If you really want to be a sadist (or you think you can/need to optimize things) then you could do the conversion 'manually' with anif
for the sign bit and a couple of/
division and%
modulus operations for the digits. \$\endgroup\$/
and%
, don't forget to add the ASCII0
character to make them printable. \$\endgroup\$