Hex value in string to int conversion and back?

I have this uart sequence.

      sequence:
        - lambda: |-
            UARTDebug::log_string(direction, bytes);
            std::string str(bytes.begin(), bytes.end());
            id(volume2).publish_state(  ?? str.substr(5,2) ??   );

The string I get from the uart is like XXXXX2F.
It is the hex value 2F I need to change into decimal value 47, but with the twist that 2F is actually a string.

I do not care if 2F is made into a hex value first and then converted or if 2 and F is converted as 2 hex values to dec. I can always multiple the first value of the 2 with 16 and add the other to the result afterwards.

When that part is solved, then I also need to get the other way to later write a decimal value to uart as a hex value in a string.
And the same here I can make an int division with 16 to get the first value in a 2 part hex value and then the modulus to get the second part, if converting hex values is easier that way.

How do I do that conversion?

https://en.cppreference.com/w/cpp/string/basic_string/stol

stoi()

There are C++ functions for that - stoi() will convert the hex string to an integer - it’s really simple:

          id(int_value) = stoi(id(hex_string), 0, 16);

For some reason going the other way is not so simple - google stringstream and you will find some examples - eg: StringStream in C++ for Decimal to Hexadecimal and back

There may be better ways…

I will try to look at it when I get back to the computer later, but it think I already tried something similar and failed, because I do not have a hex string. I have a char string. so 2F will not be 47, but rather 50 and 70.

It is working with a char string also, if I just make sure it is the right form. Thanks :slight_smile:

Now I will have to look into reverse conversion.