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?
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]);
}
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With