简体   繁体   中英

c binary file reading problems

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM