c 二进制文件读取问题

发布于 2024-09-12 17:29:48 字数 823 浏览 4 评论 0原文

您好,我正在使用 c 读取二进制文件,如下所示 链接文本

以便从二进制文件读取的所有信息都存储在“char *buffer”中。 我有格式标准,它说其中一行应该是

   format: unsigned char, size: 1 byte

我正在执行以下操作:

   printf("%x\n", buffer[N]);

但是当格式说:

   format: unsigned short, size: 2 bytes

如果我按如下方式执行时,我应该做什么,这是正确的:

   printf("%d%d\n", buffer[N], buffer[N+1]); 

如果不是,你可以告诉我正确的方法?

另外你能告诉我以下打印时是否正确:

   char              %c
   unsigned long     %ul
   unsigned short    %d
   unsigned char     %x
   double            %f
   long              %ld

二进制文件中的所有数据都是小端格式!预先非常感谢!

hi i am reading a binary file using c as shown here link text

so that all the information read from binary file is stored in "char *buffer".
i have the format standard where it says that one of the lines should be

   format: unsigned char, size: 1 byte

i am doing the following:

   printf("%x\n", buffer[N]);

but what should i do when the format says:

   format: unsigned short, size: 2 bytes

if i do it as follows, would this be correct:

   printf("%d%d\n", buffer[N], buffer[N+1]); 

if not can you show me the correct way?

Also can you tell me if the following are correct way while printing:

   char              %c
   unsigned long     %ul
   unsigned short    %d
   unsigned char     %x
   double            %f
   long              %ld

all of the data in binary file is in little-endian format! thanks a lot in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑咖 2024-09-19 17:29:48

尝试 printf("%d", (short)(buffer[N] + buffer[N+1]<<8))。现在请注意,我必须假设缓冲区中的字节顺序具有存储在较低地址的两字节 short 的最低有效字节。

我可能会写 *(short *)(&buffer[N]),但假设 N 具有正确的对齐方式以在您的平台上保存 short,并且缓冲区和平台在字节顺序上达成一致。

这实际上只是一个话题的冰山一角。当您陷入浮点值时,潜伏着许多微妙的问题,还有一些真正不微妙的问题。

Try printf("%d", (short)(buffer[N] + buffer[N+1]<<8)). Now notice that I had to assume that the byte order in the buffer had the least significant byte of the two-byte short stored at the lower address.

I could likely have written *(short *)(&buffer[N]), but that assumes that N has the right alignment to hold a short on your platform, and that the buffer and the platform agree on byte order.

This is actually just the tip of a very large iceberg of a topic. There are many subtle issues lurking, and some really unsubtle ones when you wander into floating point values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文