7

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?

Jakuje
  • 22,547
  • 12
  • 59
  • 68
Patrick
  • 969
  • 2
  • 16
  • 22

3 Answers3

16

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]);
}
Mark Stevens
  • 2,316
  • 12
  • 8
2

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...
Mike
  • 43,847
  • 27
  • 105
  • 174
0

This isn't how C works at all. If anything, you are printing the address of the buffer array.

You will need to write a subroutine that loops through each byte in the buffer and prints it to hexadecimal.

And I would recommend you start accepting some answers if you really want people to help you.

Jonathan Wood
  • 61,921
  • 66
  • 246
  • 419