-3

I am working on a project where i use a RFID reader/writer (cr500)

I got a problem on how to convert my string "FFFFFFFFFFFF" to "\xFF\xFF\xFF\xFF\xFF\xFF"

from

string key = "FFFFFFFFFFFF";

to

string raw = "\xFF\xFF\xFF\xFF\xFF\xFF";

How can this be solved using c++ standard library funcions?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

1 Answers1

1

Well, I'll take your question literally and concentrate on how to convert from the character literal "FFFFFFFFFFFF" to the target literals value of "\xFF\xFF\xFF\xFF\xFF\xFF" as you're asking for (pun intended).

Here's one way 1 to achieve what you're looking for:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

int main()
{
    std::string input = "FFFFFFFFFFFF"; // << Let's suppose this is given from the GUI
    std::istringstream iss(input);
    std::string output;
    std::string sbyte;
    while(iss >> std::setw(2) >> sbyte) {
        std::cout << sbyte << std::endl;
        std::istringstream iss2(sbyte);
        unsigned u;
        iss2 >> std::hex >> u;
        output += (unsigned char)u;
    }

    // std::string::data() contains the resulting byte values:
    for(unsigned char x : output) {
        std::cout << std::hex << "\\x" << std::setw(2) << std::setfill('0') 
                  << (unsigned)x; 
    }
    std::cout << std::endl;
}

Output:

FF
FF
FF
FF
FF
FF
\xff\xff\xff\xff\xff\xff

See Live Demo

You can control the input field width using std::setw() as shown above.


Note:

This apparently works with std::string, but not using unsigned u; directly with a former std::setw(2) directive:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

int main()
{
    std::string input = "FFFFFFFFFFFF";
    std::istringstream iss(input);
    std::string output;
    unsigned u;
    while(iss >> std::setw(2) >> std::hex >> u) {
        std::cout << std::hex << std::setw(2) << std::setfill('0') <<  u << std::endl;
        output += (unsigned char)u;
    }

    for(unsigned char x : output) {
        std::cout << std::hex << "\\x" << std::setw(2) << std::setfill('0') 
                  << (unsigned)x; 
    }
    std::cout << std::endl;
}

Live Demo


1. You can also split up your input string using std::string::substr() in a loop.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190