From: Martin Ambuhl Newsgroups: comp.os.msdos.djgpp Subject: Re: bitfields Date: Fri, 30 Apr 1999 01:49:44 -0400 Content-Transfer-Encoding: 7bit References: <925449377 DOT 992 DOT 50 AT news DOT remarQ DOT com> X-Posted-Path-Was: not-for-mail X-Accept-Language: en Content-Type: text/plain; charset=us-ascii X-ELN-Date: 30 Apr 1999 05:48:43 GMT X-ELN-Insert-Date: Thu Apr 29 22:55:06 1999 Organization: Nocturnal Aviation Lines: 59 Mime-Version: 1.0 NNTP-Posting-Host: 1cust88.tnt14.nyc3.da.uu.net Message-ID: <37294478.1FB66A48@earthlink.net> X-Mailer: Mozilla 4.51 [en] (Win95; I) To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com Ralph Allan Rice wrote: > > Hi... > > In DJGPP for x86, I wanted to program a bitfield structure like this: > > 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; > > And I want to cast it to a short int, it does not convert as expected. > > ex: > short int y = (short int) x; > > 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); Try this: #include typedef struct { unsigned field1:4; unsigned field2:4; } fields; int main(void) { fields x = { field1:0xa, field2:0xb}; /* GNUism */ unsigned short y; y = 0xff & *(unsigned short *)&x; /* To circumvent error of * assigning aggregate to * scalar; mask out high * order bytes */ printf("x contains field1=%#x, field2=%#x\n" "y contains %#x\n", x.field1, x.field2, y); return 0; } which yields: x contains field1=0xa, field2=0xb y contains 0xba -- Martin Ambuhl (mambuhl AT earthlink DOT net) Note: mambuhl AT tiac DOT net will soon be inactive