user4474372
user4474372

Reputation:

Arduino: Get Hex value from two decimal strings

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++

Upvotes: 0

Views: 308

Answers (2)

ilotXXI
ilotXXI

Reputation: 1085

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.

Upvotes: 0

Ferenc Deak
Ferenc Deak

Reputation: 35398

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

Upvotes: 1

Related Questions