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.
A string like "Hello World" to hex format: 48656C6C6F20576F726C64.
啊,给你:
#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;
}
#include <stdexcept>
int hex_value(unsigned char hex_digit)
{
static const signed char hex_values[256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
int value = hex_values[hex_digit];
if (value == -1) throw std::invalid_argument("invalid hex digit");
return value;
}
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;
}
(这里假设一个字符有 8 位,所以它不是很便携,但你可以从这里获取它.)
(This assumes that a char has 8 bits, so it's not very portable, but you can take it from here.)
相关文章