Mail Archives: djgpp/1999/05/07/02:46:28
Ralph Allan Rice wrote:
> struct codes
> {
> int field1 : 4;
> int field2: 4;
> };
>
> when I declare sucha structure, lets say like this:
>
> struct codes x;
>
> x.field1 = 0xa;
> x.field2 = 0xb;
>
> when I print out y, it results in only half of the desired result. I think
> it has to do with bitfield alignment. Is there a compiler option to set the
> alignment so that y would give me a desired result (such as 0xab or 0xba,
> but not something wierd);
The problem involves how you cast the value to a short and you have to
realize that the struct is 4 bytes long, you may only be using 8 bits of it.
You must zero out the rest of the struct:
#include<stdio.h>
typedef struct {
int a:4;
int b:4;
} bits;
int main(int argc, char *argv[])
{
bits a;
short j;
memset(&a, 0, sizeof(a));
a.a = 0xa;
a.b = 0xb;
j = *((short*)&a);
printf("%X", j);
}
--
(\/) Endlisnis (\/)
s257m AT unb DOT ca
Endlisnis AT HotMail DOT com
ICQ: 32959047
- Raw text -