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

How to Convert Between Strings and Hexadecimal in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-11 12:11:14682browse

How to Convert Between Strings and Hexadecimal in C  ?

C Conversion Between String and Hexadecimal

In C , data types can be manipulated and transformed efficiently. This includes conversions between strings and hexadecimal formats.

Converting String to Hexadecimal

To convert a string to its hexadecimal representation, a common approach is to utilize a character array of hexadecimal digits. Here's an example:

#include <string>

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;
}

In this function, the hexadecimal digits are stored in a static array for quick access. It iterates through the input string, extracting each character and representing it as two hexadecimal digits.

Converting Hexadecimal to String

To reverse the process and convert a hexadecimal string back to its original representation, you can employ the hex_to_string function:

#include <stdexcept>

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;
}

This function verifies that the input string has an even length (assuming the validity of each digit) and uses the hex_value helper function to interpret individual hexadecimal digits.

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

Statement:
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