Home > Backend Development > C++ > How to Convert Strings to Hexadecimal and Back in C ?

How to Convert Strings to Hexadecimal and Back in C ?

Mary-Kate Olsen
Release: 2024-12-19 11:25:09
Original
206 people have browsed it

How to Convert Strings to Hexadecimal and Back in C  ?

Converting Strings to Hex and Back in C

Manipulating strings and hexadecimal numbers is a common task in programming. In C , the standard library provides a set of functions for these operations.

String to Hex (string_to_hex)

Converting a string to hexadecimal is achieved using the string_to_hex function. The function iterates through each character in the input string, extracts its hexadecimal value, and appends it to the output string. For example, the string "Hello World" would be converted to "48656C6C6F20576F726C64".

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

Hex to String (hex_to_string)

To convert a hexadecimal string back to a regular string, use the hex_to_string function. Here, each pair of hexadecimal digits is converted to an integer, and the resulting integers are concatenated to form the output string.

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

This allows you to effortlessly convert between string and hexadecimal data in C , making it convenient for various programming scenarios.

The above is the detailed content of How to Convert Strings to Hexadecimal and Back 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