Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing char buffer in hex array

Tags:

c

I am reading 512 chars into a buffer and would like to display them in hex. I tried the following approach, but it just outputs the same value all the time, despite different values should be received over the network.

char buffer[512];
bzero(buffer, 512);
n = read(connection_fd,buffer,511);
if (n < 0) printf("ERROR reading from socket");
printf("Here is the message(%d): %x\n\n", sizeof(buffer), buffer);

Is it possible that here I am outputting the address of the buffer array, rather than its content? Is there an easy way in C for this task or do I need to write my own subroutine?

like image 946
Patrick Avatar asked Nov 07 '12 17:11

Patrick


2 Answers

This will read the same 512 byte buffer, but convert each character to hex on output:

char buffer[512];
bzero(buffer, 512);
n = read(connection_fd,buffer,511);
if (n < 0) printf("ERROR reading from socket");

printf("Here is the message:n\n");
for (int i = 0; i < n; i++)
{
    printf("%02X", buffer[i]);
}
like image 148
Mark Stevens Avatar answered Oct 19 '22 03:10

Mark Stevens


To display a char in hex you just need the correct format specificer and you need to loop through your buffer:

//where n is bytes back from the read:
printf("Here is the message(size %d): ", n);
for(int i = 0; i<n; i++)
     printf("%x", buffer[i]);

The code you were using was printing the address of the buffer which is why it wasn't changing for you.

Since it's been a while for you, if you'd like to see each byte nicely formatted 0xNN you can also use the %#x format:

for(int i = 0; i<n; i++)
    printf("%#x ", buffer[i]);

To get something like:

0x10 0x4 0x44 0x52...
like image 2
Mike Avatar answered Oct 19 '22 01:10

Mike