Ok, I'm sure this has been beaten to death, but google, etc. found a lot of descriptions of the problem but none of a portable solution.
I'm working with some firmware drivers which are intended to be as portable as possible. Data moves thru a switchable 8- or 16-bit data bus chip (a USB device controller specifically). Performance is critical so 16-bit is pretty much necessary. Following that example, let's look at the USB mass storage class. You get commands from the host in 31 octet command wrappers that look like this (endian issues aside...):
typedef struct { u32 Signature; u32 Tag; u32 TransferLength; u8 Flags; u8 Lun; u8 CommandLength; u8 Command[15]; } Cbw;
If I have 8 bit data types that's easy enough to get and deal with. But right now I'm working with a TMS320C55x variant with nothing smaller than 16-bit data types. So naturally the 8 bit types get all mixed up when I read them and when I send back similar data every other octet is garbage. Some responses are filled at runtime, a few are global constants. I can pack things early, but then I need to unpack, modify, and repack. Or I can pack before transmission, but that'd take a bite out of performance. Or I can break things down:
typedef struct { BYTE Signature0; BYTE Signature1; BYTE Signature2; BYTE Signature3; BYTE Tag0; BYTE Tag1; BYTE Tag2; BYTE Tag3; BYTE TransferLength0; BYTE TransferLength1; BYTE TransferLength2; BYTE TransferLength3; BYTE Flags; BYTE Lun; BYTE CommandLength; BYTE Command[15]; } Cbw;
Ugly. I'd really like to avoid that...
Now, I see this problem described countless times (yes, yes, sizeof(char)==sizeof(int)==1, 16 bit byte is 100% ok by the standard), but what's the best portable solution to dealing with this? Or at least *mostly* portable. All the messages I see say "don't store binary data and don't worry about how many bits are in anything". Great, but that embedded command field being sent from my host computer 5 meters away is 15 octets whether I like it or not. I don't care if everything's stored locally inefficiently so long as performance is reasonable (and it's clear! Other people *will* be dealing with this code!)
I'm making progress getting things to work, but it's getting ugly so I was curious how people deal with this in real life.
Thanks for whatever guidance you can provide, alex