C语言 以十六进制数组打印字符缓冲区
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13275258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing char buffer in hex array
提问by Patrick
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.
我正在将 512 个字符读入缓冲区,并希望以十六进制显示它们。我尝试了以下方法,但它始终输出相同的值,尽管应该通过网络接收不同的值。
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?
是否有可能在这里输出缓冲区数组的地址,而不是其内容?在 C 中有一个简单的方法来完成这个任务还是我需要编写自己的子程序?
回答by Mark Stevens
This will read the same 512 byte buffer, but convert each characterto hex on output:
这将读取相同的 512 字节缓冲区,但在输出时将每个字符转换为十六进制:
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]);
}
回答by Mike
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 0xNNyou can also use the %#xformat:
由于对您来说已经有一段时间了,如果您想看到每个字节的格式都很好,0xNN您还可以使用以下%#x格式:
for(int i = 0; i<n; i++)
printf("%#x ", buffer[i]);
To get something like:
得到类似的东西:
0x10 0x4 0x44 0x52...
回答by Jonathan Wood
This isn't how C works at all. If anything, you are printing the address of the bufferarray.
这根本不是 C 的工作方式。如果有的话,您正在打印buffer数组的地址。
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.
如果您真的希望人们帮助您,我建议您开始接受一些答案。

