ezp*_*sso 9 c++ string hex byte
我正在寻找一种将任意长度的字节数组转换为十六进制字符串的最快方法.StackOverflow for C#已经完全回答了这个问题.可以在这里找到C++中的一些解决方案.
是否存在问题的"交钥匙"或"现成"解决方案?欢迎使用C风格的解决方案.
Pra*_*ian 15
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <iterator>
#include <sstream>
#include <iomanip>
int main()
{
std::vector<unsigned char> v;
v.push_back( 1 );
v.push_back( 2 );
v.push_back( 3 );
v.push_back( 4 );
std::ostringstream ss;
ss << std::hex << std::uppercase << std::setfill( '0' );
std::for_each( v.cbegin(), v.cend(), [&]( int c ) { ss << std::setw( 2 ) << c; } );
std::string result = ss.str();
std::cout << result << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您有一个支持统一初始化语法和基于范围的for循环的编译器,您可以节省几行.
#include <vector>
#include <sstream>
#include <string>
#include <iostream>
#include <iomanip>
int main()
{
std::vector<unsigned char> v { 1, 2, 3, 4 };
std::ostringstream ss;
ss << std::hex << std::uppercase << std::setfill( '0' );
for( int c : v ) {
ss << std::setw( 2 ) << c;
}
std::string result = ss.str();
std::cout << result << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
std::vector<unsigned char> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
std::string res;
boost::algorithm::hex(v.begin(), v.end(), back_inserter(res));
Run Code Online (Sandbox Code Playgroud)