array of bits field
Darrin A. Hyrup
magik at sorinc.UUCP
Wed Feb 14 18:08:27 AEST 1990
In article <1990Feb12.182517.10921 at cubmol.bio.columbia.edu> ping at cubmol.bio.columbia.edu (Shiping Zhang) writes:
>Is there a way to define an array of bits field which are tightly packed?
>
>I tried the following but it caused compiling error.
>
>[... example deleted ...]
No, under standard C there is no way to do this in the way you're suggesting.
(I wish it were possible too, but alas, no.)
You do have two options.
1. Define the 16 values as an unsigned int, and use bit manipulation to
access the individual bits.
i.e., value & 0x0001 (or 1) represents the value in bit 1 of "value"
value &= 0x0040 (or 128) sets the value in bit 7 of "value" to 1
value |= ~0x0080 (or 128) sets the value in bit 8 of "value" to 0
2. Define an array of characters that is BITS_NEEDED / BITSIZE elements
long, and write routines like chkbit(), setbit(), clrbit() to access
the elements in that array.
i.e., on a system with 8 bit char's and you need 16 bits...
char bits[2];
chkbit(bits,3); returns 1 or 0 depending on the value of bit 3 in
the array bits[];
setbit(bits,4); sets bit 4 in bits[] to 1
clrbit(bits,10); sets bit 10 in bits[] to 0
This second method more closely resembles what you were originally
trying to do.
When I choose the second option, I usually use macro versions of these
routines, since the function versions added unwanted overhead. I'll
include the versions I use below for your convenience:
These macros assume an 8 bit char, and do no bounds checking.
#define chkbit(array,n) (array[n / 8] & (1 << (n % 8)))
#define setbit(array,n) (array[n / 8] |= (1 << (n % 8)))
#define clrbit(array,n) (array[n / 8] &= ~(1 << (n % 8)))
As you can see, this is just an easier way to do bit manipulations like
in example 1. If you have something other than an 8 bit char, or want to
use int's or long's instead of character arrays, change the value "8" in
the macros to the bitsize of the storage type you are using.
The main problem with the second example is that you cannot manipulate
groups of bits at the same time with it, but if you aren't going to need
it, then the second option is probably easiest.
>Thanks.
You're welcome. I hope this helps in whatever you're trying to do.
>-ping
Best wishes,
Darrin Hyrup
--
Darrin A. Hyrup // AMIGA Enthusiast rencon!esfenn!dah
magik at sorinc.PacBell.COM \X/ & Software Developer pacbell!sorinc!magik
==========================================================================
"Speak little and well, if you wish to be considered as possessing merit."
More information about the Comp.lang.c
mailing list