views:

53

answers:

4

I need to do what most packet monitoring programs do (Wireshark, tcpdump, etc.). When data is received through Winsock, I just need to convert the packet to a hex representation and save it to file.

The data is just a simple char array.

I've tried lots of things like sprintf but with no luck. I also don't want to use itoa since it's not standard C from what I've learned.

Example:

If the packet contains "test", then it should be dumped to file as "74 65 73 74".

I can do all of the file handling stuff, and the Winsock code is working, I guess I just need to write a function to convert a char array to a hex representation, and I can't seem to get it.

+4  A: 

Perhaps you should show what you have tried since printf() and its variants is by far the simplest solution.

int emit_hex( FILE* file, const char* data, size_t len )
{
    int length = 0 ;
    size_t i ;

    for( i = 0; i < len; i++ )
    {
        length += fprintf( file, "%2.2X", (unsigned)pkt[i] ) ;
        if( i < len - 1)
        {
            length += fprintf( " " ) ;
        }
    }

    return length ;
}
Clifford
I was doing it all wrong. That's a really short, simple solution, thanks.
guitar-
+1  A: 

sprintf uses the %x conversion for hex, so you'd typically use something like this:

cvt2hex(unsigned len, char const *input, char *output) { 
    int i;
    for (i=0; i<len; i++)
        sprintf(output+i*3, "%2.2x ", input[i]);
}

Of course, output needs to point to enough memory to hold the converted data. You'll typically want to insert a new-line after every 16 or 32 bytes, or somewhere in that vicinity.

Jerry Coffin
+3  A: 
loentar
Didn't need all that info but that's just like Wireshark does it and I learned a lot from it, thanks a bunch.
guitar-
A: 

Another way is to use a length modifier for char (hh):

printf("%hhx", c);
ninjalj