Home > Backend Development > C++ > How to Efficiently Convert Between Hexadecimal Strings and Standard Strings in C ?

How to Efficiently Convert Between Hexadecimal Strings and Standard Strings in C ?

Patricia Arquette
Release: 2024-12-15 22:23:13
Original
914 people have browsed it

How to Efficiently Convert Between Hexadecimal Strings and Standard Strings in C  ?

Converting Hexadecimal Strings to Strings in C

String conversion between hexadecimal and standard text formats requires a robust approach in C . Here's a detailed guide:

Convert String to Hexadecimal:

The string_to_hex() function offers a simple solution:

std::string string_to_hex(const std::string& input) {
    static const char hex_digits[] = "0123456789ABCDEF";
    std::string output;
    output.reserve(input.length() * 2);
    for (unsigned char c : input) {
        output.push_back(hex_digits[c >> 4]);
        output.push_back(hex_digits[c & 15]);
    }
    return output;
}
Copy after login

Convert Hexadecimal to String:

For converting from hexadecimal to string, the hex_to_string() function ensures accuracy:

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;
}
Copy after login

Example Usage:

To demonstrate the functionality:

std::string original_string = "Hello World";
std::string hex_string = string_to_hex(original_string);
std::cout << "Hexadecimal representation: " << hex_string << std::endl;
std::string recovered_string = hex_to_string(hex_string);
std::cout << "Recovered string: " << recovered_string << std::endl;
Copy after login

Output:

Hexadecimal representation: 48656c6c6f20576f726c64
Recovered string: Hello World
Copy after login

The above is the detailed content of How to Efficiently Convert Between Hexadecimal Strings and Standard Strings in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template