64,654
社区成员
发帖
与我相关
我的任务
分享
#include <string>
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
class PrintHex : public unary_function<char, void>
{
public:
explicit PrintHex(string &str) : str_(str) {}
result_type operator()(argument_type x)
{
str_.append(1, HexStr[((x & 0xf0) >> 4)]);
str_.append(1, HexStr[(x & 0x0f)]);
}
private:
string &str_;
static const char HexStr[];
};
const char PrintHex::HexStr[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
#define ARRAY_SIZE(X) (sizeof(X)/sizeof(X[0]))
int main(int argc, char* argv[])
{
string str;
char a[12] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c};
for_each(a, a + ARRAY_SIZE(a), PrintHex(str));
cout << str << "\n";
return 0;
}
char a[12]={0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c};
char sz[200] = {0};
for (int i = 0; i < 12; ++ i)
{
sprintf(sz + 2*i, "%02x", a[i]);
}