c 二进制文件读取问题
您好,我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试 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-byteshort
stored at the lower address.I could likely have written
*(short *)(&buffer[N])
, but that assumes that N has the right alignment to hold ashort
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.