Search code examples
c++carduinoitoa

Arduino C function to convert String to HEX?


I am looking for built-in C or C++ function that allows me to convert a float into an HEX string, so far I have used itoa , but it does not work with negative values since it works with unsigned for base 16, so I was wondering which one I could use instead that may handle the negative value.

Using itoa I loose my negative value as it can be seen below,

Acceleration X: -9 | X angle: **-0.5156689167**
Acceleration Y: -69 | Y angle: **-3.9565520286**
Acceleration Z: 986 | Z angle: 80.4013519287
Value of ACC per axe (x,y,z) in HEX ->ffcdfe751f68
Data to be send x ->**ffcd**
Data to be send y ->**fe75**
Data to be send z ->1f68

What other function could I use with the same functionality?


Solution

  • Looking at the results you provided I would say they are correct. You got the binary complement values:

    ffcd = -51 in 16-Bit binary complement
    fe75 = -395 in 16-Bit binary complement
    1f68 = 8040 in 16-Bit binary complement
    

    Devide it by 100 and you get your (rounded) floating point values.

    atoi can handle negative values. It indicates the negative status by setting the most valued Bit of the binary representation to 1. You will not get a - sign, if you did expect one.

    You can compute the binary complement by yourself by converting the (16-Bit) HEX value to a decimal and substract 65536 from the result.

    e.g

    ffcd -dec-> 65485 -sub-> 65485 - 65536 = -51 -float-> -51 / 100.0 = - 0.51