Portable arrays of bits

Thomas Paul Brisco brisco at caip.RUTGERS.EDU
Fri Nov 7 02:04:54 AEST 1986


>Is there a standard, machine independant way of defining an array 
>of bits?  I am writing code and do not want to have to do a function
>call each time I reference a bit, but want a Boolean array packed
>as tightly as possible.


	The immediate (and naive) approach is to say:
	struct{
		bit:1
		}[LOTS]

	However, C does not support bit fields directly. For every bit
field it will allocate a full word. This is distressing particularly
if you have a sparse structure, and many of them.

	A better approach is to define a subroutine or macro as
following:

#define getbit(x,p) ((x >> p)&~(~0 << 1))

	This is from K&R (God bless 'em). A "setbit" macro could be
fudged up fairly similiarly.  Of course for this to work *really*
good, you should make sure that the struct uses char's ,not int's --
vaxes have a (literally) twisted concept of how bytes fit into ints.
By using chars you avoid the little/big -endian problems. Also, you'll
probably want (somewhere) a #define for the number of bits in a
character (just to cover all bases) for computational purposes.

	The structure I used look like this:
	unsigned char bitmap[1024][1024]
and used the previous macro as a sub-routine to reference bits within
the char's.  I set bits by simple multiplications.




				tp.
-- 
                  ----------------------------------------------------------
                  -                  ARPA: Brisco at rutgers                  -
                  -  UUCP: (ihnp4!ut-sally, allegra!packard) !caip!brisco  -
                  ----------------------------------------------------------



More information about the Comp.lang.c mailing list