如何在C++中将十六进制字符串转换为字节字符串?
How to convert hex string into byte string in C++?
我正在寻找在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;
}
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将这个std::字符串转换为std::基本字符串
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 如何在C++中将十六进制字符串转换为文本数据
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何从字符串转换为双精度*
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- 如何将整数字符串转换为整数的二维向量?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 将文件复制到自定义位置,存在字符串转换问题
- 将ANSI C字符串转换为UNICODE
- 如何将节点 V8 字符串转换为 C++ 字符串
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将字符串转换为无符号字符数组/字节数组