On 03/09/2011 08:34 AM, dspfun wrote:
> On 9 mar, 10:40, Ben Bacarisse<ben.use...@bsb.me.uk> wrote:
>> What advantage do you hope to get from using unsigned short rather than
>> unsigned int for bit-fields? �I can't see why you don't want to use
>> unsigned int as the type.
>
> The reason is that two bytes are sent from a big endian cpu and "we"
> receive it on a little endian cpu. To access the information in the
> two bytes I declare a struct with bit-fields.
The standard deliberately under-specifies the layout of structs, and
this is particularly true for bit fields. As a result, you cannot
portably rely upon the bits from the data you're transferring being in
the same location as the bits corresponding to any particular bit field.
If portability isn't an issue, then there's no problem; but for
maximally portable code, your best option is to use a unsigned char
buffer, and extracting the bits by using shift and mask operations.
This still isn't perfect: such code usually relies upon CHAR_BITS==8,
which is also not guaranteed. However, you can at least check at compile
time whether CHAR_BITS==8, and chose an appropriate alternative if it is
not. You cannot determine at compile time which bits of a struct
correspond to a given bit field, though there are ways to do so at run time.
--
James Kuyper
|