views:

62

answers:

1

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!

+2  A: 

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.

RBerteig
@RBerteig: thanks! can you tell if these are correct: char - %c,unsigned long - %ul, unsigned short - %d, unsigned char - %x, double - %f, long - %ld.
sdfg
@sdfg, you've got a mix of right and wrong there. Start with the man page for printf(3), and then read about serialization. Google is likely your friend.
RBerteig