PDA

View Full Version : output in HEX format


greka
May 29, 2004, 10:37
I wonder if some needs such utility.
This function allows to present (print) binary data stream in hexadecimal format.

void OutputInHexFormat(char *pBuf, int iLen)
{
#define OUTPUTWIDTH 50
static char outputBuf[300];
int i, intCtr, iLenStr;

char tmp[20];
char *pCursor;

memset(outputBuf, 0, sizeof(outputBuf));
pCursor = outputBuf;

intCtr = 0;
for (i = 0; i < iLen; i++)
{
sprintf(tmp, "%02x ", pBuf[i] & (int)0xFF);
iLenStr = strlen(tmp);
intCtr += iLenStr;

strcat(pCursor, tmp); // append new data
pCursor += iLenStr; // advance destination pointer

// check the output width:
if ( ( pCursor - outputBuf ) > OUTPUTWIDTH-1 )
{
printf(" %s\n", outputBuf );
pCursor = outputBuf; // reset to the begin
// prepare the storage:
memset(outputBuf, 0, intCtr*sizeof(char) );
}
}

printf(" %s\n", outputBuf );
}

To make it faster use table of strings {"00", "01", "02", ..., "ff "} instead of constructing string each time:

sprintf(tmp, "%02x ", pBuf[i] & (int)0xFF);

also replace this call iLenStr = strlen(tmp); to iLenStr = 3;

Agregat
May 29, 2004, 11:39
1. Зачем & в sprintf - е. Массив так и так байтов, больше 255 не будет.

#include <sstream>
#include <iomanip>
#include <vector>
#include <iostream>
#include <iterator>

void printHex(const char * pBuf, const int iLen, const int iWidth, std::ostream & os) {
std::ostringstream ss;
for (int i = 0; i < iLen; ++i)
ss << std::hex << std::setw(2) << std::setfill('0') << (int)pBuf[i];
const std::string s = ss.str();
const int iRowCount = s.length() / iWidth + 1;
for (int i = 0; i < iRowCount; ++i)
os << s.substr(i * iWidth, iWidth) << std::endl; //must not crash on standard compliant string realization.
}

int main() {
//read as much as we can
std::vector<char> v((std::istream_iterator<char>(std::cin)), std::istream_iterator<char>());
printHex(&v.front(), v.size(), 78, std::cout); //standart output width
return 0;
}

мое решение, но Ц++ :)

Agregat
May 29, 2004, 11:41
Да, в догонку, для тех у кого VC6 int i во втором цикле объявлять не надо, просто i = 0;