简体   繁体   中英

Parsing string to hex value in C++ on Arduino

I have the IR code in form of hexadecimal stored in string (without 0x prefix) which has to be transmited via sendNEC() from IRremote.h . What's the easiest way to convert string in form like "FFFFFF" to 0xFFFFFF ?

This is a dirty code which works well under severe limitations:

  • no error checking needed
  • string format is exactly known and is F...F'\\0'
  • it is assumed that codes for '0' to '9' and 'A' to 'F' are subsequent and growing

The trick is to use character codes for calculations _

char * in;
uint64_t out=0;
int counter;

for(counter=0; in[counter]; counter++){
    if(in[counter]>='0'&&in[counter]<='9') {
        out*=0x10;
        out+=in[counter]-'0';
    } else {
    //assuming that character is from 'A' to 'F'
        out*=0x10;
        out+=in[counter]-'A'+10;
    }
}

if you get every char of the string and converted to a numeric hex value then you will need only to calculate the power of every digit, that conversion returns a number which can be represented in several ways (hex in your case)

std::string w("ABCD");
unsigned int res = 0;
for (int i = w.length()-1; i >= 0; i--)
{
    unsigned int t = parseCharToHex(w[w.length() - 1 - i]);
    std::cout << std::hex << t << std::endl;
    res += pow(16, i) * t;
}

std::cout << "res: " << std::dec << res << std::endl;

the function parseCharToHex :

unsigned int parseCharToHex(const char charX)
{
    if ('0' <= charX && charX <= '9') return charX - '0';
    if ('a' <= charX && charX <= 'f') return 10 + charX - 'a';
    if ('A' <= charX && charX <= 'F') return 10 + charX - 'A';
}

pow function is required from the arduino doc here

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM