繁体   English   中英

C++ 将十六进制字符串表示形式转换为十六进制

[英]C++ Convert Hex String Representation to Hex

我在这里搜索了答案,但要么没有找到,要么没有理解。

我需要将 std::string 诸如“F1F2F3F4”(8 字节)转换为字节 \\xF1\\xF2\\xF3\\xF4(4 字节)。

我需要std::hex但我对我看到的例子感到困惑。 转换后,我需要访问这些字节(作为字符数组),以便我可以将它们从 EBCDIC 转换为 ASCII(但那是另一回事了)。

所以我认为它会是这样的:

somevariable << std::hex << InputString;

但是我应该使用什么作为变量? 顺便说一下,InputString 可以是从 1 到 50 左右的任意长度。

我的编译器是 Linux 上的 g++ 4.8。

一个简单(有点天真)的方法是一次从输入字符串中获取两个字符,放入另一个字符串,然后将其传递给std::stoi (如果没有std::stoi ,则传递给std::strtoul ) 转换为整数,然后您可以将其放入字节数组中。

例如这样的事情:

std::vector<uint8_t> bytes;  // The output "array" of bytes
std::string input = "f1f2f4f4";  // The input string

for (size_t i = 0; i < input.length(); i += 2)  // +2 because we get two characters at a time
{
    std::string byte_string(&input[i], 2);  // Construct temporary string for
                                            // the next two character from the input

    int byte_value = std::stoi(byte_string, nullptr, 16);  // Base 16
    bytes.push_back(byte_value);  // Add to the byte "array"
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM