简体   繁体   中英

How to convert Hex string to text data in C++

I have a variable which is giving data in hex strings as follows: 68 73 2d 3c 40 40 9d 46 3c.... I want to convert this data to text format.

I have a some code. this code is giving false and unreadable data.

int hex_value(char hex_digit)
{
    switch (hex_digit) {
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9':
        return hex_digit - '0';

    case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
        return hex_digit - 'A' + 10;

    case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
        return hex_digit - 'a' + 10;
    }
    throw std::invalid_argument("invalid hex digit");
}

std::string hex_to_string(const std::string& input)
{
    const auto len = input.length();
    if (len & 1) throw std::invalid_argument("odd length");

    std::string output;
    output.reserve(len / 2);
    for (auto it = input.begin(); it != input.end(); )
    {
        int hi = hex_value(*it++);
        int lo = hex_value(*it++);
        output.push_back(hi << 4 | lo);
    }
    return output;
}

When ever I run this code my program crashes. Thank you.

You may use std::stoi function with int base = 16 to convert string to int:

int main(int, char**)
{
    std::cout << "Value=" << std::stoi("ff", nullptr, 16) << std::endl;
    std::cout << "Value=" << std::stoi("0A", nullptr, 16) << std::endl;
    std::cout << "Value=" << std::stoi("ffff", nullptr, 16) << std::endl;
    return 0;
}

Output
Value=255
Value=10
Value=65535

For your example:

std::string convert(const std::string& Input) {
    if (Input.empty() || Input.size() % 2 != 0) {
        throw std::invalid_argument("invalid argument");
    }

    std::string result, piece;

    for (auto it = Input.begin(); it != Input.end(); it += 2) {
        piece = std::string(&(*it), 2);
        result += std::stoi(piece, nullptr, 16);
    }
    return result;
}

int main(int, char**)
{
    std::cout << convert("48656c6c6f20776f726c64") << std::endl;
    return 0;
}
Output
Hello world
#include <sstream>
#include <iostream>

int main() {
    unsigned int x;   
    std::stringstream ss;
    ss << std::hex << "fffefffe";
    ss >> x;
    // output it as a signed type
    std::cout << static_cast<int>(x) << std::endl;
}

the simplest answer for newer code would probably look like this: (from C++11)

std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);
// this function is only for two charcter separted hex string ,like your input 
// hex string input charcter should be in lower case 
std::string HexToText( std::string & input )
{  int temp[2]; std::string r_str;
   for(int i=0;i<input.size();i+=3)
     {  temp[0]=0; temp[1]=0;
     
       if(isdigit(input[i]))  //if input character is digit then minus 48 to convert into int
          temp[0]= 16*(int)(input[i]-48);
       else
          temp[0]=16*(int)(input[i]-87);
          /* if input character is not digit then it would be from [a-e]
             'a' ascii is 97 and it's decimal is 10 .
             so 97-x = 10 
                 >> x=87
          */
                 
      // same for byte[1]
       if(isdigit(input[i+1]))  
           temp[1]= (int)(input[i+1]-48);
        else
           temp[1]=(int)(input[i+1]-87);
           
       // add and push
       r_str.push_back((char)(temp[0]+temp[1]));
     } 
   return r_str;
}

Happy coding !

in this case the stl class stringstream may be useful:



std::string hex_to_string(const std::string& input)
{
    std::string output;
    std::istringstream iss(input);
    iss.setf(std::istringstream::hex, std::istringstream::basefield);

    while (!iss.eof()) {

        unsigned int n;
        iss >> n;

        if (iss.fail() || iss.bad())
            break;

        output += static_cast<char>(n);

    }

    return output;
}


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