0

I would like to do a conversion but don't know how.

Originally I get a Hex value like 03 EE which represents 1006. Now those data is represent in a String array and as decimals:

[0] = "3"
[1] = "238"

Whats the easiest way to get back to a decimal 1006 from this situation?

I do this on an Arduino with C++

mnille
  • 1,328
  • 4
  • 16
  • 20
  • well you need to apply the same algorithm backwards : convert each field into its hexadecimal string representation, concatenate all strings and convert the new string into its numerical hexadecimal representation – specializt Aug 03 '16 at 11:40
  • @Kai Just interesting: where do you get this string from? – ilotXXI Aug 03 '16 at 14:36
  • It's from the CAN bus of my car. The string represents the engines current RPM. –  Aug 04 '16 at 07:44

2 Answers2

1

Something like this should do it:

const char* s[] = {"3", "238"};

int result = (std::stoi(std::string(s[0])) << 8)
          + std::stoi(std::string(s[1]));
std::cout << result;

Please note that I use std::stoi, if you don't like it, please see for more conversion possibilities at: Convert string to int C++

live example

Community
  • 1
  • 1
Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
0

As Arduino's String cannot process hex representations, you should do it manually or with another libraries (e.g. using sprintf from standard C library, if it is possible). Here is a manual way:

int decBytesToInt(const String &msByte, const String &lsByte)
{
    int res = 0;
    res |= (msByte.toInt() & 0xFF) << 8;
    res |= (lsByte.toInt() & 0xFF);
}

msByte and lsByte are most significant and least significant bytes decimal representations correspondingly.

Supposed that int is 16-bit, of course.

ilotXXI
  • 1,075
  • 7
  • 9