Re: Help on bit operation

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Ben, after assign all bitfield struct member, how to pack them to be a
32bit integer value?

DEC      BIN
43        101011        -> foo.a (6 bit)
11        1011            -> foo.b (4 bit)
120      01111000    -> foo.c (8 bit)
30        11110          -> foo.d (5 bit)
418      110100010  -> foo.e (9 bit)

the bit pattern is : 10101110110111100011110110100010 or 2933800354 in
decimal, is this possible?

while with masking and shift i can pack them with:
((foo.a & 0x3f) << 26) | ((foo.b & 0xf) << 22) | ((foo,c & 0xff) <<
14) | ((foo.d & 0x1f) << 9) | (foo.e & 0x1ff)


On Sat, Aug 29, 2009 at 12:02 AM, Ben Rosenberg<scdlbx@xxxxxxxxx> wrote:

> Glynn's example of bitfields is cleaner and better than this, but I
> put a basic implementation of bitfields using your parameters at the
> end of this message. From my understanding, the way bitfields are
> implemented in C is with bit shifts and masks, so I don't think there
> is a performance difference between the two.
>
> #include <stdio.h>
>
> struct bitfield {
>    unsigned int a:6;
>    unsigned int b:4;
>    unsigned int c:8;
>    unsigned int d:5;
>    unsigned int e:9;
> };
>
> int main(void) {
>    struct bitfield foo;
>    foo.a =  43;
>    foo.b =  11;
>    foo.c = 120;
>    foo.d =  30;
>    foo.e = 418;
>    printf("%u %u %u %u %u\n",foo.a,foo.b,foo.c,foo.d,foo.e);
>    return 0;
> }
>
>
> Ben
>
--
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html

[Index of Archives]     [Linux Assembler]     [Git]     [Kernel List]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [C Programming]     [Yosemite Campsites]     [Yosemite News]     [GCC Help]

  Powered by Linux