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

时间:2019-10-01 15:36:57

标签: 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 ..." */

有没有执行此功能的库函数?

1 个答案:

答案 0 :(得分:0)

不存在执行任务的标准函数。但是,自己编写合适的方法并不困难。

例如,您可以使用普通循环或标准算法,例如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;
}
相关问题