0

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?

Nikola Stojaković
  • 2,257
  • 4
  • 27
  • 49

2 Answers2

1

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

enter image description here

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

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;
    }
}
Euri Pinhollow
  • 332
  • 2
  • 17