C ++将字符串转换为十六进制,反之亦然 [英] C++ convert string to hexadecimal and vice versa

查看:225
本文介绍了C ++将字符串转换为十六进制,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to convert a string to hex and vice versa in C++?

示例:


  • 字符串Hello World到十六进制格式: 48656C6C6F20576F726C64

  • 从十六进制 48656C6C6F20576F726C64 到字符串:Hello World

  • A string like "Hello World" to hex format: 48656C6C6F20576F726C64
  • And from hex 48656C6C6F20576F726C64 to string: "Hello World"

推荐答案


一个字符串,如Hello World,十六进制格式:48656C6C6F20576F726C64。 p>

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

(假设一个char有8位,但你可以从这里带走。)

(This assumes that a char has 8 bits, so it's not very portable, but you can take it from here.)

这篇关于C ++将字符串转换为十六进制,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆