www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/04/15/10:38:49

Message-ID: <D1FB30BBA491D1118E6D006097BCAE39267FA7@Probe-nt-2a.Probe.co.uk>
From: Shawn Hargreaves <ShawnH AT Probe DOT co DOT uk>
To: djgpp AT delorie DOT com
Subject: Re: Individual Bits
Date: Wed, 15 Apr 1998 10:48:12 +0100
MIME-Version: 1.0

Sergio Vale e Pace writes:
>    I'm trying to make a struct to work something like this:
>
> defined_struct data;
> data=8;
> data.bit0=1; // data=9
> data.bit2=1; //data=13


Try something like:


	#include <stdio.h>


	typedef union STUFF
	{
	    int all;

	    struct {
	        int bit0 : 1;
	        int bit1 : 1;
	    } parts;

	} STUFF;


	int main()
	{
	    STUFF t;

	    t.all = 8;
	    printf("%d\n", t.all);

	    t.parts.bit0 = 1;
	    printf("%d\n", t.all);

	    t.parts.bit1 = 1;
	    printf("%d\n", t.all);

	    return 0;
	}


I'm not sure how reliable the ordering of these bitfield variables
will be across different compilers and endian formats, though. My 
personal tendency is to avoid such explicit bitfields, and do any
binary packing myself with the C logical operators, eg. "val |= 1" 
to set a bit and "val &= ~1" to clear it. That way you always know
exactly how the data is ordered, plus your code will be portable
to pre-ANSI compilers that don't support packed bitfields.


	Shawn Hargreaves.

- Raw text -


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