How to pack struct in C for non-aligned data?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Henry Yiu

    #1

    How to pack struct in C for non-aligned data?

    In the following structure, bytesPerSector is not aligned to the sizeof(short), so after I read the raw data into buffer, and try to extract the bytesPerSector portion, I got the wrong number. Is there a easy fix for this? I am using Visual C++ Express on a x86 processor.

    Code:
    struct BS_Structure {
    	unsigned char     jumpBoot[3];
    	unsigned char     OEMName[8];
    	unsigned short    bytesPerSector;
    	unsigned char     sectorPerCluster;
    } ptr;
    
    unsigned char buffer[512];
    unsigned short bytesize;
    
    ReadSDCard (buffer);
    ptr = (BS_Structure*) buffer;
    bytesize = ptr->bytesPerSector;
    Last edited by Atli; Nov 19 '10, 04:56 PM. Reason: Please use [code] tags when posting code.
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    bytesPerSector should indeed be properly aligned. What makes you think is isn't? An alignment problem will typically show up with a run-time error message, not improper operation.

    Are you sure you don't overflow the bounds of the jumpBoot or OEMName arrays?

    Comment

    • newb16
      Contributor
      • Jul 2008
      • 687

      #3
      If the specification of the structure says something like 'on position 11 and 12 there is a 16-bit value'( yes it does - http://en.wikipedia.org/wiki/Fat16#Boot_Sector ) you need to manually extract them from the raw data, like
      unsigned short bytesPerSector = raw[12] << 8 | raw[11];
      Hoping that a compiler propery align it is not reliable. Endianness also matters.

      Comment

      Working...