c++ - 如何在 C++ 中将十六进制字符串转换为字节字符串?

标签 c++ string algorithm hex

<分区>

我正在寻找在 C++ 中将十六进制字符串转换为字节字符串的方法。 我想像下面的伪代码一样将 s1 转换为 s2。 to_byte_string 的输出必须是 std::string

std::string s1 = "0xb5c8d7 ...";
std::string s2;

s2 = to_byte_string(s1) /* s2 == "\xb5\xc8\xd7 ..." */

有没有库函数可以做这种事情?

最佳答案

没有这样一个标准的函数来完成任务。但是自己写一个合适的方法并不难。

例如,您可以使用普通循环或标准算法,例如 std::accumulate。

这是一个演示程序

#include <iostream>
#include <string>
#include <iterator>
#include <numeric>
#include <cctype>

int main() 
{
    std::string s1( "0xb5c8d7" );

    int i = 1;
    auto s2 = std::accumulate( std::next( std::begin( s1 ), 2 ),
                               std::end( s1 ),
                               std::string(),
                               [&i]( auto &acc, auto byte )
                               {
                                    byte = std::toupper( ( unsigned char )byte );
                                    if ( '0' <= byte && byte <= '9' ) byte -= '0';
                                    else byte -= 'A' - 10;

                                    if ( i ^= 1 ) acc.back() |= byte;
                                    else acc += byte << 4;

                                    return acc;
                               } );

    return 0;
}

关于c++ - 如何在 C++ 中将十六进制字符串转换为字节字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58188186/

相关文章:

c++ - std::get() 如何与 std::tuple 一起工作?

java - 获取和跳过字符串组?

javascript - 对表示时间的字符串进行排序并取最接近的

algorithm - 设置绘制二叉树的位置

c++ - Visual Studio 2010 - 在不同的构建配置之间保留项目属性?

c++ - 迷你UPnP文档

c++ - 我可以制作一个从其基础继承的模板特化吗?

c - 使用指针到指针从二维数组打印字符串

Python - 将数字的因子按排序顺序放入数组

algorithm - 关于图中的二分集和独立集