[comp.lang.c] Portable arrays of bits

zben@umd5 (Ben Cranston) (11/10/86)

In article <3862@caip.RUTGERS.EDU> brisco@caip.RUTGERS.EDU (Thomas Paul Brisco) writes:

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

> A better approach is to define a subroutine or macro as following:
> #define getbit(x,p) ((x >> p)&~(~0 << 1))

Unless your hardware has a barrel-shifter this can cost you lots of cycles.
I usually define a structure like:

char bitsmask[8] = { 1, 2, 4, 8, 16, 32, 64, 128 };

and do operations like:   if ( x[p/8] & bitsmask[p%8] ) ...
or setting them like:     x[p/8] |= bitsmask[p%8];

The idea is that an 8 byte table is cheap, and is perhaps faster than a
shift instruction.  I have done this with a 32 word table of ints as well.
It does seem to be difficult to parameterize for different word lengths tho.
-- 
                    umd5.UUCP    <= {seismo!umcp-cs,ihnp4!rlgvax}!cvl!umd5!zben
Ben Cranston zben @ umd2.UMD.EDU    Kingdom of Merryland Sperrows 1100/92
                    umd2.BITNET     "via HASP with RSCS"