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
  • 24,773
  • 12
  • 69
  • 75
Patrick
  • 989
  • 3
  • 16
  • 23
  • 1
    possible duplicate of [Printing the hexadecimal representation of a char array\[\]](http://stackoverflow.com/questions/10375932/printing-the-hexadecimal-representation-of-a-char-array) – Ciro Santilli OurBigBook.com Jun 27 '15 at 21:58

3 Answers3

19

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,366
  • 14
  • 9
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
  • 47,263
  • 29
  • 113
  • 177
-1

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
  • 65,341
  • 71
  • 269
  • 466