By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,949 Members | 889 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,949 IT Pros & Developers. It's quick & easy.

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

P: n/a
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.

Expand|Select|Wrap|Line Numbers
  1. struct BS_Structure {
  2.     unsigned char     jumpBoot[3];
  3.     unsigned char     OEMName[8];
  4.     unsigned short    bytesPerSector;
  5.     unsigned char     sectorPerCluster;
  6. } ptr;
  7.  
  8. unsigned char buffer[512];
  9. unsigned short bytesize;
  10.  
  11. ReadSDCard (buffer);
  12. ptr = (BS_Structure*) buffer;
  13. bytesize = ptr->bytesPerSector;
  14.  
Nov 19 '10 #1
Share this Question
Share on Google+
2 Replies


Expert 100+
P: 2,396
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?
Nov 19 '10 #2

100+
P: 687
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.
Nov 20 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.