C将字符串转换为十六进制,反之亦然

什么是最好的方式将字符串转换为十六进制,反之亦然在C?

例:

>类似“Hello World”的字符串到十六进制格式:48656C6C6F20576F726C64
>从十六进制48656C6C6F20576F726C64到字符串:“Hello World”

最佳答案

A string like “Hello World” to hex format: 48656C6C6F20576F726C64.

啊,在这里你去:

#include <string>

std::string string_to_hex(const std::string& input)
{
    static const char* const lut = "0123456789ABCDEF";
    size_t len = input.length();

    std::string output;
    output.reserve(2 * len);
    for (size_t i = 0; i < len; ++i)
    {
        const unsigned char c = input[i];
        output.push_back(lut[c >> 4]);
        output.push_back(lut[c & 15]);
    }
    return output;
}

#include <algorithm>
#include <stdexcept>

std::string hex_to_string(const std::string& input)
{
    static const char* const lut = "0123456789ABCDEF";
    size_t len = input.length();
    if (len & 1) throw std::invalid_argument("odd length");

    std::string output;
    output.reserve(len / 2);
    for (size_t i = 0; i < len; i += 2)
    {
        char a = input[i];
        const char* p = std::lower_bound(lut, lut + 16, a);
        if (*p != a) throw std::invalid_argument("not a hex digit");

        char b = input[i + 1];
        const char* q = std::lower_bound(lut, lut + 16, b);
        if (*q != b) throw std::invalid_argument("not a hex digit");

        output.push_back(((p - lut) << 4) | (q - lut));
    }
    return output;
}

(这假设一个字符有8位,所以它不是很便携,但你可以从这里。)

转载注明原文:C将字符串转换为十六进制,反之亦然 - 代码日志