将一段字符串排版化输出,左边是其十六进制显示,右边是字符显示。代码:
void print_file(const byte* debuff, int src_len, const char*file_path)
{
std::ofstream file(file_path, std::ios::out|std::ios::app);
if (file)
{
//file << "the " << g_nPacketCount << " packet" << std::endl;
for (int len = src_len; len>0; len-=8)//每8个字节一组
{
string s;
string s2 = " ";//间隔符
if (len>=8)
{
for(int i=0; i<8; i++)
{
int index = src_len-len+i;
string st = bytesToHexString(&debuff[index], 1);
s.append(st);
s.append(" ");
if (debuff[index]==0x0a || debuff[index]==0x0d)//过滤掉字符串中的换行符
s2.append(" ");
else
s2.append(1, debuff[index]);
}
}
else
{
s2.append((8-len)*3, ' ');
for(int i=0; i<len; i++)
{
int index = src_len-len+i;
string st = bytesToHexString(&debuff[index], 1);
s.append(st);
s.append(" ");
if (debuff[index]==0x0a || debuff[index]==0x0d)
s2.append(" ");
else
s2.append(1, debuff[index]);
}
}
file << s << s2;//输出到文件
file << std::endl;
}
file << std::endl << std::endl ;
file.close();
}
}
string BytesToHexString(const byte *in, size_t size) {
string str;
for (size_t i = 0; i < size; ++i) {
int t = in[i];
int a = t / 16;
int b = t % 16;
str.append(1, IntToHexChar(a));
str.append(1, IntToHexChar(b));
if (i != size - 1)
str.append(1, ' ');
}
return str;
}
char IntToHexChar(int x) {
static const char HEX[16] = {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'A', 'B',
'C', 'D', 'E', 'F'
};
return HEX[x];
}
std::string gstr_file_path = argv[1];
//gstr_key = argv[2];
size_t pos = gstr_file_path.rfind(".");
string st = gstr_file_path.substr(0,pos+1);
st.append("txt");
gstr_file_path = st;