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

How to convert hex string into byte string in C++?

本文关键字:字符串 转换 字节 十六进制 C++      更新时间:2023-10-16

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

std::string s1 = "0xb5c8d7 ...";
std::string s2;
s2 = to_byte_string(s1) /* s2 == "xb5xc8xd7 ..." */

有没有库函数来做这种事情?

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

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