Print char buffer in hexadecimal array

I am reading 512 characters into the buffer and would like to display them in hexadecimal format. I tried the following approach, but it just outputs the same value all the time, despite the fact that different values ​​have to be taken 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 was displaying the address of the buffer, and not its contents? Is there an easy way in C for this task, or do I need to write my own routine?

+4
source share
3 answers

This will read the same 512-byte buffer, but convert each character to hexadecimal 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]); } 
+8
source

This is not how C generally works. Anyway, you print the address of the buffer array.

You will need to write a routine that iterates over each byte in the buffer and prints it in hexadecimal format.

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

0
source

To display char in hexadecimal format, you just need the correct format specifier, and you need to go through the 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 used printed the address of the buffer, so it did not change.

Since it took you some time if you want each byte to be nicely formatted with 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... 
0
source

Source: https://habr.com/ru/post/1444633/


All Articles