Re: [Hampshire] [Slightly OT] Arduino coding help - pointers…

Top Page

Reply to this message
Author: Chris Liddell
Date:  
To: Hampshire LUG Discussion List
Subject: Re: [Hampshire] [Slightly OT] Arduino coding help - pointerstostructs
On 03/08/2010 15:28, Hugo Mills wrote:
> On Tue, Aug 03, 2010 at 02:44:42PM +0100, Chris Liddell wrote:
>> On 03/08/2010 14:30, Hugo Mills wrote:
>>> On Tue, Aug 03, 2010 at 02:19:32PM +0100, Chris Liddell wrote:
>>>> Declarations like your code don't declare variables comprising that
>>>> number of bits, they still are still the size of the base type (in this
>>>> case unsigned int). All the bit length option does (if supported by the
>>>> compiler) is restrict the maximum value of the field (and sometimes not
>>>> even that - many compilers ignore it completely).
>>>>
>>>> So your structure is not 16 bits long, it's 192 bits long.
>>>
>>>    Not true, at least with gcc 4.4.4:

>>>
>>> hrm@shades:~$ cat <<EOF >foo.c
>>>> #include <stdio.h>
>>>>
>>>> struct received_data {
>>>>     unsigned int start:1;
>>>>     unsigned int address:4;
>>>>     unsigned int command:5;
>>>>     unsigned int flags:4;
>>>>     unsigned int padding:1;
>>>>     unsigned int parity:1;
>>>> };

>>>>
>>>> int main(int argc, char* argv[])
>>>> {
>>>> printf("%d\n", sizeof(struct received_data));
>>>> return 0;
>>>> }
>>>> EOF
>>> hrm@shades:~$ gcc foo.c
>>> hrm@shades:~$ ./a.out
>>> 4
>>
>> Ah, that's interesting. It *definitely* used to use the base type.
>
>    Not for as long as I've been writing C, which is >mumblety< years,
> now. :)  A lot of the bit-packed struct specification is
> implementation-defined anyway, so maybe I've just never met a compiler
> that does it that way.


Hmm, now I think about it, when I ran into these issues, it may have
been on PPC or SPARC hardware, or MIPS, or Alpha or ARM...... <sigh>

>
>> Mind you, four bytes is rather strange, since that doesn't seem to fit
>> with the structure element alignment - I'd have thought six bytes would
>> be the minimum size it could be. I *thought* gcc at least defaulted to
>> processor word alignment.
>

<SNIP>
>    "Processor word alignment" is rather a vague concept to handle on
> x86/amd64, due to 30 years of history. It's rather clearer on, say,
> Alpha, where non-aligned accesses cause a hardware exception, or early
> ARM, where they cost more CPU cycles to do. :)

>
>    I'm not sure how you arrive at the value of 6 bytes (unless that's
> a typo for 8 bytes, assuming that it's a 64-bit machine).


If the minimum alignment was a byte, each element in struct
received_data is less than 8 bits (so padded for alignment) and there
are six elements.

Anyway, you're right, I fell into the same trap (from different
direction) giving a platform specific answer.....

Chris