www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/05/07/02:46:28

From: Endlisnis <s257m AT unb DOT ca>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: bitfields
Date: Wed, 05 May 1999 17:43:54 -0400
Organization: BrunNet
Lines: 52
Message-ID: <3730BB9A.6C51E702@unb.ca>
References: <925449377 DOT 992 DOT 50 AT news DOT remarQ DOT com>
NNTP-Posting-Host: ftnts2c33.brunnet.net
Mime-Version: 1.0
X-Mailer: Mozilla 4.04 [en] (Win95; U)
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:

> 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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019